Kodeclik Logo

Our Programs

Courses

Learn More

Schedule

Kodeclik Blog

How to iterate through a Python dictionary

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:

mydict = dict(Apples=2.5, Oranges=5.5, Bananas=1.2)
print(mydict)

This gives the output:

{'Apples': 2.5, 'Oranges': 5.5, 'Bananas': 1.2}

There are many other ways to initialize a dictionary. See our blogpost on initializing Python dictionaries for more details.

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.

Python Iterate through Dictionary

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:

mydict = dict(Apples=2.5, Oranges=5.5, Bananas=1.2)
for key in mydict.keys():
  print(key)

This gives the output, as expected:

Apples
Oranges
Bananas

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):

mydict = dict(Apples=2.5, Oranges=5.5, Bananas=1.2)
for key in sorted(mydict.keys()):
  print(key)

The output will be:

Apples
Bananas
Oranges

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.

mydict = dict(Apples=2.5, Oranges=5.5, Bananas=1.2)
for val in mydict.values():
  print(val)

Note that in the above code, we have replaced the keys() method with the values() method. The output of the code is thus:

2.5
5.5
1.2

Let us do as before and try to return them in sorted order (of values):

mydict = dict(Apples=2.5, Oranges=5.5, Bananas=1.2)
for val in sorted(mydict.values()):
  print(val)

The output is:

1.2
2.5
5.5

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:

mydict = dict(Apples=2.5, Oranges=5.5, Bananas=1.2)
for a, b in mydict.items():
  print(a,b)

The output is:

Apples 2.5
Oranges 5.5
Bananas 1.2

We can combine the ideas from the earlier methods to return the items in sorted order (by default this uses sorting of keys):

mydict = dict(Apples=2.5, Oranges=5.5, Bananas=1.2)
for a, b in sorted(mydict.items()):
  print(a,b)

The output is:

Apples 2.5
Bananas 1.2
Oranges 5.5

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:

mydict = dict(Apples=2.5, Oranges=5.5, Bananas=1.2)
for a, b in {**mydict}.items():
  print(a,b)

The output is:

Apples 2.5
Oranges 5.5
Bananas 1.2

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:

mydict = dict(Apples=2.5, Oranges=5.5, Bananas=1.2)
newdict = dict(Grapes = 4, Pineapples=3)
for a, b in {**mydict,**newdict}.items():
  print(a,b)

The output is:

Apples 2.5
Oranges 5.5
Bananas 1.2
Grapes 4
Pineapples 3

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.

mydict = dict(Apples=2.5, Oranges=5.5, Bananas=1.2)
newdict = dict(Grapes = 4, Pineapples=3)
totalprice = 0
for a, b in {**mydict,**newdict}.items():
  totalprice = totalprice + b
print("Total price = ", totalprice)

The output is:

Total price =  16.2

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:

mydict = dict(Apples=2.5, Oranges=5.5, Bananas=1.2)
newdict = dict(Grapes = 4, Pineapples=3)
totalprice = 0
finaldict = dict()
for a, b in {**mydict,**newdict}.items():
  finaldict[b] = a
print(finaldict)

The output is:

{2.5: 'Apples', 5.5: 'Oranges', 1.2: 'Bananas', 
 4: 'Grapes', 3: 'Pineapples'}

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:

mydict = dict(Apples=2.5, Oranges=5.5, Bananas=1.2)
newdict = dict(Grapes = 2.5, Pineapples=3)
totalprice = 0
finaldict = dict()
for a, b in {**mydict,**newdict}.items():
  finaldict[b] = a
print(finaldict)

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:

{2.5: 'Grapes', 5.5: 'Oranges', 1.2: 'Bananas', 3: 'Pineapples'}

You have learnt many different ways to iterate through a dictionary. Which one is your favorite? If you would like to learn more about dictionaries, learn about initializing a Python dictionary,, working with an empty dictionary, and finding the length of a dictionary. Also learn how to use dictionaries to compute a histogram.

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!

Want to learn Python with us? Sign up for 1:1 or small group classes.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

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.

Copyright @ Kodeclik 2024. All rights reserved.