How to Iterate Over a Dictionary in Python

How to Iterate Over a Dictionary in Python

Introduction

Dictionaries are one of the most used data structures in all of software development, and for a good reason. They allow us to store our data in neat key, value pairs, which in turn gives us the ability to, on average, access our data in O(1) time.

While using a dictionary it's important to know how to iterate over it. Not being able to recover the data you stored makes it practically useless.

In this article, we'll see how to iterate through a Python dictionary with all kinds of iterators and the for loop.

Using the keys() Method

Python dictionaries have a handy method which allows us to easily iterate through all initialized keys in a dictionary, keys().

Keep in mind that since Python 3, this method does not return a list, it instead returns a view object. A view object is exactly like the name says, a view of some data.

This means that we can iterate through said data no problem, but if we want to actually store the list of keys, we need to materialize it. Which can easily be done by forwarding the provided view object to a list constructor.

Let's take a look at how it all works:

my_dict = {'alpha': 5, 'beta': 4, 'gamma': 3}

# Here we're just 'looking' at the keys,
# we're not actually constructing a list 
# out of them
key_view = my_dict.keys()
print("Key view:", key_view)
print("Type:", type(key_view),end="\n\n")

# Here we're materializing the keys
# into a list ofo keys
key_list = list(my_dict.keys())
print("Key list:", key_list)
print("Type: ", type(key_list),end="\n\n")

# And as we can see, view can be easily be
# used for iterating over a dictionary
for key in my_dict.keys():
    print(key, ':', my_dict[key]) 

Running the code gives us the following output:

Key view: dict_keys(['alpha', 'beta', 'gamma'])
Type: <class 'dict_keys'>

Key list: ['alpha', 'beta', 'gamma']
Type:  <class 'list'>

alpha : 5
beta : 4
gamma : 3 

An alternative way of doing this would be:

my_dict = {'alpha': 5, 'beta': 4, 'gamma': 3}

for key in my_dict:
    print(key, ':', my_dict[key])

When using the in keyword in conjunction with a dictionary, the dictionary invokes its __iter__() method. This method then returns an iterator which is used to implicitly go through the keys of the provided dictionary.

Using the values() Method

Just like the keys() method, the values() method also return a view object, but instead of iterating through keys, it iterates through values:

my_dict = {'alpha': 5, 'beta': 4, 'gamma': 3}

# Inspecting the view of the values
# in the dictionary
key_list = list(my_dict.values())
print("Value list:", key_list)
print("Type: ", type(key_list), end="\n\n")

for value in my_dict.values():
    print(value, end=" ")

Running the code gives us the following output:

Value list: [5, 4, 3]
Type:  <class 'list'>
5 4 3 

Unlike the previous method, this one only provides values. It is useful when you are not concerned about keys.

Using the items() method

Just like the keys() and values() methods, the items() method also returns a view object, but instead of just iterating through either keys or values, it iterates through (key,value) pairs.

Let's take a look at how it all works:

my_dict = {'alpha': 5, 'beta': 4, 'gamma': 3}

# Inspecting the view of the (key,value) pairs
key_list = list(my_dict.items())
print("(key,value) pair list:", key_list)
print("Type: ", type(key_list), end="\n\n")

for item in my_dict.items():
    print(item, end=" ")

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Running the code gives us the following output:

(key,value) pair list: [('alpha', 5), ('beta', 4), ('gamma', 3)]
Type:  <class 'list'>
('alpha', 5) ('beta', 4) ('gamma', 3) 

To immediately assign both keys and values simultaneously, we can use tuple unpacking and extract them by using variables for each value in a tuple:

for key, value in my_dict.items():
    print(key,':',value)

It is important to note that in older Python 2 versions where items(), keys(), and values() returned a copy of data from a dictionary. While in Python 3 they return a view object.

These are more effective as they provide a dynamic view and, additionally if any changes are made in the original dictionary, they will immediately be reflected in the view object (and vice versa).

Conclusion

In this article, we've covered different ways to iterate over a Python dictionary. This includes the keys(), values() and items() methods, with a for loop.

Last Updated: January 22nd, 2021
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Want a remote job?

    Prepping for an interview?

    • Improve your skills by solving one coding problem every day
    • Get the solutions the next morning via email
    • Practice on actual problems asked by top companies, like:
     
     
     

    Better understand your data with visualizations

    With over 330+ pages, you'll learn the ins and outs of visualizing data in Python with popular libraries like Matplotlib, Seaborn, Bokeh, and more.

    © 2013-2021 Stack Abuse. All rights reserved.