codescracker


python

Python Dictionary



« Previous Tutorial Next Tutorial »


Dictionary in python is same as real life dictionary book, as in dictionary, you can store your information in the form of key-value pair. Here key represent the word (the dictionary word) and value is its definition just like the definition in dictionary book.

Using dictionary in python, you can organize your information.

Since in dictionary book, you find a word to get its definition, in the same way, here in python dictionary, you can find a key to get its value.

Dictionary are simply the kind of hash table type. Dictionary in python, works like associative arrays or hashes found in Perl and consists of key-value pairs.

Create Dictionary in Python

Dictionaries are enclosed within the curly braces {}. Here is an example shows how to create a dictionary in python.

my_dictionary = {'Name': 'Devraj','Id':9388, 'Branch': 'CSE'};

As you can see from the above example code, there are three key and its three values. Here are the list of keys and values from the above example:

Key Value
Name Devraj
Id 9388
Branch CSE

Access Dictionary Values in Python

You can access values from dictionary using the square braces [] as shown in the following example.

my_dictionary[name];

Above code will access the value of the key name, that is Devraj from the above code as given in creating dictionary in python.

Python Dictionary Example

Here is an example program, demonstrates the concept and use of dictionary in python:

# Python Dictionary - Example Program

dictionary1 = {}
dictionary1['one'] = "This is one"
dictionary1[2]     = "This is two"

smalldictionary = {'name': 'Devraj','id':9388, 'branch': 'cs'}

print(dictionary1[2])             # this will print the values for 2 key
print(dictionary1['one'])         # this will print the value for 'one' key
print(smalldictionary)            # this will print the complete dictionary
print(smalldictionary.keys())     # this will print all the keys
print(smalldictionary.values())   # this will print all the values 

Here is the sample output of the above python program:

python dictionary

Now let's suppose that i have a dictionary with following key-values pairs:

my_dictionary = {"google": "it is a search engine, provides you the information related to your query.",
		"youtube": "it is video-sharing portal, provides you to watch and upload videos.",
		"codescracker": "it is a computer programming portal, where one can learn and find exclusive codes.",
		"english": "it is a language."};

According to the above dictionary, let's learn about some other topics of dictionary given below.

Accessing Value using Key from Dictionary

To access any value from the dictionary using its key in python, use the following syntax or general form.

word = input("\nEnter word to find out its meaning:");
if word in my_dictionary:
	word_def = my_dictionary[word];
	print(word_def);
else:
	print("not found!");

As you can see from the above code fragment, value can be accessed using its key by putting it inside the square bracket.

Above code will initialize the value of the key say word to the another variable say word_def and later prints the value of this variable, which will be the value of entered key.

Adding a Key-Value Pair to Dictionary

To add a new key-value pair to the dictionary in python, use the following technique.

word = input("\nEnter word to include in dictionary:");
if word not in my_dictionary:
	word_def = input("Enter its definition or meaning:");
	my_dictionary[word] = word_def;
	print(word,"successfully added to the dictionary.");
else:
	print("already exists!");

Replacing or Updating a Key-Value Pair in Python

To replace or update a key-value pair that is already exists in the dictionary in python, then use the technique given below.

word = input("\nEnter word to update:");
if word in my_dictionary:
	word_def = input("Enter new definition:");
	my_dictionary[word] = word_def;
	print(word,"has been updated successfully.");
else:
	print("not found!");

Deleting a Key-Value Pair from Dictionary

To delete an existed key-value pair from the dictionary in python, then here is the technique you have to follow.

 word = input("\nEnter word to delete it form dictionary:");
if word in my_dictionary:
	del my_dictionary[word];
	print(word,"deleted from dictionary successfully.");
else:
	print("not found!");

Python Dictionary Complete Program

Now let's take the complete program of all the above action performing on the dictionary, my_dictionary, that is, accessing dictionary values, adding a new key-value pairs, replacing or updating a key-value pairs, deleting a key-value pairs from the dictionary in python.

This example, first gives users, some number of choices, here from 0 to 4 choices, that is total of 5 choices, to perform the action just by entering the choice number and following the next instruction asked by the program.

All the choices are given in this program using while loop in python.

In this example, in operator is used to check whether required word or key is present inside the dictionary or not.

The del keyword in this example is used to delete the key-value pair. Now let's go through the following program.

my_dictionary = {"google": "it is a search engine, provides you the information related to your query.",
                 "youtube": "it is video-sharing portal, provides you to watch and upload videos.",
                 "codescracker": "it is a computer programming portal, where one can learn and find exclusive codes.",
                 "english": "it is a language."};
choice = None;
while choice != "0":
    print("\n\tMy Dictionary");
    print("0 - Exit");
    print("1 - Search for Word");
    print("2 - Add Word to Dictionary");
    print("3 - Update a Word");
    print("4 - Delete a Word from Dictionary");
    choice = input("Enter your choice:");
    if choice == "0":
        print("\nExiting...bubye..");
    elif choice == "1":
        word = input("\nEnter word to find out its meaning:");
        if word in my_dictionary:
            word_def = my_dictionary[word];
            print(word_def);
        else:
            print("not found!");
    elif choice == "2":
        word = input("\nEnter word to include in dictionary:");
        if word not in my_dictionary:
            word_def = input("Enter its definition or meaning:");
            my_dictionary[word] = word_def;
            print(word,"successfully added to the dictionary.");
        else:
            print("already exists!");
    elif choice == "3":
        word = input("\nEnter word to update:");
        if word in my_dictionary:
            word_def = input("Enter new definition:");
            my_dictionary[word] = word_def;
            print(word,"has been updated successfully.");
        else:
            print("not found!");
    elif choice == "4":
        word = input("\nEnter word to delete it form dictionary:");
        if word in my_dictionary:
            del my_dictionary[word];
            print(word,"deleted from dictionary successfully.");
        else:
            print("not found!");
    else:
        print("\nChoice is not valid!");

Here is the sample output produced by the above complete program of python dictionary. This is the initial output.

python dictionary example

Now provide 1 as choice and enter a word (key) to find its information (value) related to that word as given in the following screenshot of sample output produced after performing this action.

dictionary in python

Now, this time, provide 2 as choice and follow the instruction given in the above program as shown in the following screenshot.

dictionary in python example

Now it's time to provide 1 as choice to check out the word Python included or added earlier, that is it really added or not as shown below.

create dictionary python

Now, provide 3 as choice to check the updating feature of the dictionary in python as shown below.

accessing dictionary values python

Now again it's time to provide 1 as choice to search google to find whether it is really updated or not as shown below.

adding key value pair python

Now this time, provide 4 as choice to check the deletion feature of python dictionary as shown in the following screenshot.

replacing key value pair python

Now again use 1 as choice and search for the term youtube that is deleted earlier, whether is it really deleted or not as shown below.

deleting key value pair python

Now, finally, give 0 as output to exit from the program.

getting dictionary value python

Now, let's see the complete output in three part of all the above action performed one by one.

This is first full screen output window:

python dictionary program

This is second full screen output window:

python dictionary code

This is the third and last full screen output window:

dictionary example python

« Previous Tutorial Next Tutorial »








Tools
Calculator

Quick Links
Signup - Login - Give Online Test