Recall that a dictionary in Python is an associative array. A dictionary is a set of key-value pairs so specific values can be associated with specific keys. For instance, we can have a dictionary of food products in a grocery store (keys) and their prices (values).
You can create a dictionary with the dict constructor:
Now that we have a dictionary, we can aim to iterate through them. For instance, we might want to go through the dictionary and print each item in turn. Or we might want to use iteration to add up all the prices to determine how much we would pay if we purchased one item of each kind.
Iterating through a Python dictionary with the keys() method
The first approach we will use uses the keys() method to loop over the dictionary. Here is how that works:
This gives the output, as expected:
In the above code, the keys() method when applied to a dictionary returns an iterable and we use that iterable in a for loop to obtain each key in succession.
You can also update the code above to return the keys in sorted order (here, alphabetical):
The output will be:
Iterating through a Python dictionary with the values() method
As you might have guessed, the values() method returns the values in the dictionary rather than the keys. This is a second way to iterate through the dictionary.
Note that in the above code, we have replaced the keys() method with the values() method. The output of the code is thus:
Let us do as before and try to return them in sorted order (of values):
The output is:
as expected.
Iterating through a Python dictionary with the items() method
The items() method returns both keys and values and you can use it akin to a Python enumerate construct:
The output is:
We can combine the ideas from the earlier methods to return the items in sorted order (by default this uses sorting of keys):
The output is:
Iterating through multiple Python dictionaries with the unpacking operator
This method is suitable for iterating through multiple dictionaries. Let us first see how it works with a single dictionary:
The output is:
Here “**” is the dictionary unpacking operator that returns each element of the dictionary one by one. To see why this is useful consider the following code that iterates through multiple dictionaries:
The output is:
Note that each application of ** returns the elements of that dictionary and essentially this way of programming flattens and merges the elements of multiple dictionaries into a single iterable.
Summing through the elements of a Python dictionary
Let us put the skills we have learnt to good use. Let us try to use iteration to add up all the prices to determine how much we would pay if we purchased one item of each kind.
The output is:
as expected.
Creating new dictionaries from existing dictionaries
Let us try to use the dictionary unpacking operator to merge two dictionaries into a new dictionary with values as the keys and the keys as the values:
The output is:
Note that the keys are now prices and the values are the names of the items.
You have to be careful with code like this because if two elements have the same price and you are turning the price into a key then Python will use the newer assignment to determine the value corresponding to that key. Let us modify the price of Grapes to simulate this scenario:
Note that both Apples and Grapes have a price of 2.5. Using the dictionary unpacking operator the last assignment for a key of 2.5 will be ‘Grapes’ and therefore when we print the dictionary we will get:
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.