Looping through Dictionary in PYTHON

A single Python dictionary can contain just a few key-value pairs or millions of pairs. Because a dictionary can contain large amounts of data, Python lets you loop through a dictionary. Dictionaries can be used to store information in a variety of ways; therefore, several different ways exist to loop through them. You can loop through all of a dictionary’s key-value pairs, through its keys, or through its values.

Looping Through All Key-Value Pairs

Before we explore the different approaches to looping, let’s consider a new dictionary designed to store information about a user on a website. The following dictionary would store one person’s username, first name, and last name:

user_0 = {
    'username': 'efermi',
    'first': 'enrico',
    'last': 'fermi',
    }

You can access any single piece of information about user_0 based on what you’ve already learned in this chapter. But what if you wanted to see everything stored in this user’s dictionary? To do so, you could loop through the dictionary using a for loop:

user.py

   user_0 = {
       'username': 'efermi',
       'first': 'enrico',
       'last': 'fermi',
       }

➊ for key, value in user_0.items():
➋     print(f"\nKey: {key}")
➌     print(f"Value: {value}")

As shown at ➊, to write a for loop for a dictionary, you create names for the two variables that will hold the key and value in each key-value pair. You can choose any names you want for these two variables. This code would work just as well if you had used abbreviations for the variable names, like this:

for k, v in user_0.items()

The second half of the for statement at ➊ includes the name of the dictionary followed by the method items(), which returns a list of key-value pairs. The for loop then assigns each of these pairs to the two variables provided. In the preceding example, we use the variables to print each key ➋, followed by the associated value ➌. The “\n” in the first print() call ensures that a blank line is inserted before each key-value pair in the output:

Key: username
Value: efermi

Key: first
Value: enrico

Key: last
Value: fermi

Looping through all key-value pairs works particularly well for dictionaries like the favorite_languages.py example which stores the same kind of information for many different keys. If you loop through the favorite_languages dictionary, you get the name of each person in the dictionary and their favorite programming language. Because the keys always refer to a person’s name and the value is always a language, we’ll use the variables name and language in the loop instead of key and value. This will make it easier to follow what’s happening inside the loop:

favorite_languages.py

   favorite_languages = {
       'jen': 'python',
       'sarah': 'c',
       'edward': 'ruby',
       'phil': 'python',
       }

➊ for name, language in favorite_languages.items():
➋     print(f"{name.title()}'s favorite language is {language.title()}.")

The code at ➊ tells Python to loop through each key-value pair in the dictionary. As it works through each pair the key is assigned to the variable name, and the value is assigned to the variable language. These descriptive names make it much easier to see what the print() call at ➋ is doing.

Now, in just a few lines of code, we can display all of the information from the poll:

Jen’s favorite language is Python.
Sarah’s favorite language is C.
Edward’s favorite language is Ruby.
Phil’s favorite language is Python.

This type of looping would work just as well if our dictionary stored the results from polling a thousand or even a million people.

Looping Through All the Keys in a Dictionary

The keys() method is useful when you don’t need to work with all of the values in a dictionary. Let’s loop through the favorite_languages dictionary and print the names of everyone who took the poll:

   favorite_languages = {
       'jen': 'python',
       'sarah': 'c',
       'edward': 'ruby',
       'phil': 'python',
       }

➊ for name in favorite_languages.keys():
       print(name.title())

The line at ➊ tells Python to pull all the keys from the dictionary favorite_languages and assign them one at a time to the variable name. The output shows the names of everyone who took the poll:

Jen
Sarah
Edward
Phil

Looping through the keys is actually the default behavior when looping through a dictionary, so this code would have exactly the same output if you wrote . . .

for name in favorite_languages:

rather than . . .

for name in favorite_languages.keys():

You can choose to use the keys() method explicitly if it makes your code easier to read, or you can omit it if you wish.

You can access the value associated with any key you care about inside the loop by using the current key. Let’s print a message to a couple of friends about the languages they chose. We’ll loop through the names in the dictionary as we did previously, but when the name matches one of our friends, we’ll display a message about their favorite language:

   favorite_languages = {
       --snip--
       }

➊ friends = ['phil', 'sarah']
   for name in favorite_languages.keys():
       print(f"Hi {name.title()}.")

➋     if name in friends:
➌         language = favorite_languages[name].title()
           print(f"\t{name.title()}, I see you love {language}!")

At ➊ we make a list of friends that we want to print a message to. Inside the loop, we print each person’s name. Then at ➋ we check whether the name we’re working with is in the list friends. If it is, we determine the person’s favorite language using the name of the dictionary and the current value of name as the key ➌. We then print a special greeting, including a reference to their language of choice.

Everyone’s name is printed, but our friends receive a special message:

Hi Jen.
Hi Sarah.
    Sarah, I see you love C!
Hi Edward.
Hi Phil.
    Phil, I see you love Python!

You can also use the keys() method to find out if a particular person was polled. This time, let’s find out if Erin took the poll:

   favorite_languages = {
       'jen': 'python',
       'sarah': 'c',
       'edward': 'ruby',
       'phil': 'python',
       }

➊ if 'erin' not in favorite_languages.keys():
       print("Erin, please take our poll!")

The keys() method isn’t just for looping: it actually returns a list of all the keys, and the line at ➊ simply checks if ‘erin’ is in this list. Because she’s not, a message is printed inviting her to take the poll:

Erin, please take our poll!

Looping Through a Dictionary’s Keys in a Particular Order

Starting in Python 3.7, looping through a dictionary returns the items in the same order they were inserted. Sometimes, though, you’ll want to loop through a dictionary in a different order.

One way to do this is to sort the keys as they’re returned in the for loop. You can use the sorted() function to get a copy of the keys in order:

favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
    }

for name in sorted(favorite_languages.keys()):
    print(f"{name.title()}, thank you for taking the poll.")

This for statement is like other for statements except that we’ve wrapped the sorted() function around the dictionary.keys() method. This tells Python to list all keys in the dictionary and sort that list before looping through it. The output shows everyone who took the poll, with the names displayed in order:

Edward, thank you for taking the poll.
Jen, thank you for taking the poll.
Phil, thank you for taking the poll.
Sarah, thank you for taking the poll.

Looping Through All Values in a Dictionary

If you are primarily interested in the values that a dictionary contains, you can use the values() method to return a list of values without any keys. For example, say we simply want a list of all languages chosen in our programming language poll without the name of the person who chose each language:

favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
    }

print("The following languages have been mentioned:")
for language in favorite_languages.values():
    print(language.title())

The for statement here pulls each value from the dictionary and assigns it to the variable language. When these values are printed, we get a list of all chosen languages:

The following languages have been mentioned:
Python
C
Ruby
Python

This approach pulls all the values from the dictionary without checking for repeats. That might work fine with a small number of values, but in a poll with a large number of respondents, this would result in a very repetitive list. To see each language chosen without repetition, we can use a set. A set is a collection in which each item must be unique:

   favorite_languages = {
       --snip--
       }

   print("The following languages have been mentioned:")
➊ for language in set(favorite_languages.values()):
       print(language.title())

When you wrap set() around a list that contains duplicate items, Python identifies the unique items in the list and builds a set from those items. At ➊ we use set() to pull out the unique languages in favorite_languages.values().

The result is a nonrepetitive list of languages that have been mentioned by people taking the poll:

The following languages have been mentioned:
Python
C
Ruby

As you continue learning about Python, you’ll often find a built-in feature of the language that helps you do exactly what you want with your data.

NOTE

You can build a set directly using braces and separating the elements with commas:

>>> languages = {‘python’, ‘ruby’, ‘python’, ‘c’}
>>> languages
{‘ruby’, ‘python’, ‘c’}

It’s easy to mistake sets for dictionaries because they’re both wrapped in braces. When you see braces but no key-value pairs, you’re probably looking at a set. Unlike lists and dictionaries, sets do not retain items in any specific order.

TRY IT YOURSELF

Rivers: Make a dictionary containing three major rivers and the country each river runs through. One key-value pair might be ‘nile’: ‘egypt’.

Use a loop to print a sentence about each river, such as The Nile runs through Egypt.

Use a loop to print the name of each river included in the dictionary.

Use a loop to print the name of each country included in the dictionary.

Written by

XR Developer responsible for end-to-end development of XR solutions spanning multiple domains, by using various XR and WebXR libraries.

Leave a Reply