How to Iterate Over a Dictionary in Python

by | Programming, Python, Tips

The easiest way to iterate over a dictionary is to use the in operator with a for loop. For example,

for i in dict:

    print(i)

iterate over the keys in the dictionary. We can use square brackets together with the keys to retrieve the values in the dictionary. For example:

for i in dict:

    print(dict[i])

This tutorial will go through how to iterate over a dictionary using a for loop, the keys(), values(), and items() methods with examples.


Introduction

A Python dictionary is a built-in Python container that stores elements as a key-value pair. As of Python version 3.7, a dictionary is an ordered collection that is mutable and does not allow duplicates. For versions before 3.7, dictionaries are unordered. We can write dictionaries using curly brackets to contain the key-value pairs. Let’s look at an example of a dictionary to store the characteristics of the muon particle:

muon_dict = {
"mass": 105.7,
"charge": -1,
"spin": 1/2,
}
print(muon_dict)
{'mass': 105.7, 'charge': -1, 'spin': 0.5}

The left-hand side of the colon is the key, and the right-hand side is the value. A single key-value pair is a dictionary item, and we can refer to a dictionary item using the key name.

Iterate Over Dictionary Using a for Loop

We can iterate directly over a Python dictionary using a for loop. The iteration procedure implicitly calls the __iter__() method, which returns an iterator allowing us to iterate over a dictionary’s keys. Let’s use the for loop to iterate over the muon dictionary:

muon_dict = {
"mass": 105.7,
"charge": -1,
"spin": 1/2,
}
for key in muon_dict:
    print(key, '-≻', muon_dict[key])

In the for loop, we use the indexing operator [] and the dictionary’s keys to access the values and print them to the console. Let’s run the code to get the result: ≻

mass -≻ 105.7
charge -≻ -1
spin -≻ 0.5

Iterate Over Dictionary Using keys()

You can iterate over a dictionary using the keys() method. This method returns a new view object of the type dict_keys that holds a list of all keys. Let’s look at calling the keys() method on the muon dictionary:

muon_dict = {
"mass": 105.7,
"charge": -1,
"spin": 1/2,
}

k = muon_dict.keys()

print(k)
dict_keys(['mass', 'charge', 'spin'])

We can see that the keys() method returns a view object containing the list of keys in the muon dictionary. We can iterate over the dictionary by calling the keys() method in a for loop, as follows:

for key in muon_dict.keys():

    print(key, '-≻', muon_dict[key])

In the for loop, we use the indexing operator [] and the dictionary’s keys to access the values and print them to the console. Let’s run the code to get the result:

mass -≻ 105.7
charge -≻ -1
spin -≻ 0.5

Iterate Over Dictionary Using values()

You can iterate over a dictionary using the values() method. This method returns a new view object of the type dict_values that holds a list of all values. Let’s look at calling the values() method on the muon dictionary:

muon_dict = {
"mass": 105.7,
"charge": -1,
"spin": 1/2,
}

v = muon_dict.values()

print(v)
dict_values([105.7, -1, 0.5])

We can see that the values() method returns a view object containing the list of values in the muon dictionary. We can iterate over the dictionary by calling the values() method in a for loop, as follows:

for value in muon_dict.values():

    print(value)

Using the values() method, you will access only values of the dictionary without handling the keys. Let’s run the code to see the result:

105.7
-1
0.5

Iterate Over Dictionary Using items()

You can iterate over a dictionary using the items() method. Calling this method returns a view object of the type dict_items that contains a list of the key-value pairs in a dictionary. Let’s call the items() method on the muon dictionary.

muon_dict = {
"mass": 105.7,
"charge": -1,
"spin": 1/2,
}

items = muon_dict.items()

print(items)
dict_items([('mass', 105.7), ('charge', -1), ('spin', 0.5)])

We can see that the dict_items view object contains a list of key-value tuples for the muon dictionary. We can iterate over the items in the dictionary by calling the items() method in a for loop, as follows:

for item in muon_dict.items():

    print(item)

Let’s run the code to see the result:

('mass', 105.7)
('charge', -1)
('spin', 0.5)

We can use tuple unpacking to access the keys and values within the tuples as follows:

for key, value in muon_dict.items():

    print(key, '-≻', value) 

mass -≻ 105.7
charge -≻ -1
spin -≻ 0.5

Summary

Congratulations on reading to the end of this tutorial! You have gone through how to iterate over a dictionary in Python. The easiest way to do this is to use a for loop directly on the dictionary. You can use call the keys(), values(), and items() methods to return a view object that you can iterate over with a for loop. Dictionary view objects are dynamic, reflecting any changes made to a dictionary. You can use tuple unpacking with the items() method to access the keys and values.

For further reading on dictionaries, go to the articles: 

Go to the Python online courses page to learn more about coding in Python for data science and machine learning.

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee