You Design. We HTML.

A Smooth Refresher on Python’s Dictionaries

February 1, 2016 - Uncategorized

In a previous tutorial, I talked about a very versatile and flexible object type in Python, namely Lists. In this article, I continue my refreshers with another flexible Python object type called Dictionaries (also called associative arrays or hashes). Like the List, the Dictionary is an important concept to grasp in order to move forward in your Python journey.

What Is a Dictionary Anyway?

If you went through the Lists article, it will be easy to understand the concept of Dictionaries. They are pretty much like Lists but with two main differences: 

  1. They are unordered sets (unlike Lists which are ordered).
  2. Keys are used to access items and not a position (i.e. index).

Each key in the Dictionary has a value, which could be of any Python object type. That is, Dictionaries can be considered as key-value pairs. But, be careful that keys cannot be of types List or Dictionary.

Let’s Create an English-French Dictionary

As we saw in the previous section, a Dictionary is simply an unordered set of key-value pairs. Let’s use this concept to create our first example, an English-French dictionary. This Dictionary can be created as follows:

english_french = {'paper':'papier', 'pen':'stylo', 'car':'voiture', 'table':'table','door':'porte'}

The Dictionary english_french contains five English words set as keys with their French meanings set as values

Let’s say we wanted to know how to say pen in French. We simply do the following:


where you will get stylo as the value returned.

Making Things More Interesting

Let’s say we had a french_spanish Dictionary with the same words we had in the english_french Dictionary, as follows:

french_spanish = {'papier':'papel', 'stylo':'pluma', 'voiture':'coche', 'table':'mesa', 'porte':'puerta'}

Well, you have been asked how to say door in Spanish, and you don’t have an English-Spanish dictionary on hand! But, don’t worry, there is a solution. Consult your english_french Dictionary for the word, then use the result to consult the french_spanish Dictionary. Got the point? Let’s see how we can do that in Python:


The result should be puerta. Isn’t that very nice? You just got the word for door in Spanish although you don’t have an English-Spanish dictionary.

More Operations on Dictionaries

In the previous example we saw how we can create a Dictionary and access items in the Dictionary. Let’s see some more operations we can make on Dictionaries. I’m going to use the english_french Dictionary in the examples below.

How Many Entries Are There in the Dictionary?

In other words, this operation is meant to return the number of key-value pairs in the Dictionary. This can be performed using the len() operator, as follows:


You should get 5 returned.

Deleting a Key

The deletion of an item in a Dictionary is carried out through the keys. For instance, let’s say we wanted to delete the word (key) door from the Dictionary. This can be simply done as follows:

del english_french['door']

This will remove the key door along with its value porte.

Does the Key Exist in the Dictionary?

In the previous sub-section, we removed the key door from the Dictionary. If we want to check if door still exists in the Dictionary or not, we type:

'door' in english_french

which should return False.

Thus, what do you think the following statement will return? Go ahead and give it a try (notice the not).

'door' not in english_french

What happens if we try to access a key that doesn’t exist in a Dictionary? Say english_french['door']. In this case, you would get an error similar to the following:

Traceback (most recent call last):

  File "", line 7, in <module>

    print english_french['door']

KeyError: 'door'

Creating a Copy of Your Dictionary

You may need a copy of your english_french Dictionary and assign that to another Dictionary. This can be simply done using the copy() function, as follows:

new_english_french = english_french.copy()

Nested Dictionaries

As we mentioned above, values in Dictionaries can be of any type, including Dictionaries. This is referred to as Nesting. An example of this can be as follows:

student = {'ID':{'name':'Abder-Rahman', 'number':'1234'}}

Thus, if you type student['ID'], you should get:

{'name': 'Abder-Rahman', 'number': '1234'} 

Iterating Over a Dictionary

Let’s come back to the english_french Dictionary. There are many ways in which you can iterate over the Dictionary’s items:

for word in english_french:

    print word

The result of this statement is as follows:






Notice that the keys in the result are not given in the same order as in the english_french Dictionary. You can now see why I said that Dictionaries are considered unordered sets.

Another way of iterating through keys is as follows:

for word in english_french.iterkeys():

    print word

Notice that we used the iterkeys() function. A similar function that can be used to iterate through the values, namely itervalues(), is as follows:

for meaning in english_french.itervalues():

    print meaning

The result in this case should look something like the following:






Alternative Ways of Creating Dictionaries

There are alternative ways of creating a Dictionary in Python using the dict constructor. Some examples of creating the same Dictionary ID using dict are as follows:

ID = dict(name = 'Abder-Rahman', number = 1234)

ID = dict([('name','Abder-Rahman'),('number',1234)])

ID = dict(zip(['name','number'],['Abder-Rahman',1234])) # keys and values as Lists

There is more that you can do with Dictionaries. Check Python’s documentation for more information.

Source: Photoshop | Tuts

Leave a Reply

Your email address will not be published. Required fields are marked *