Skip to content

Effortlessly Iterate Through Dictionary in Python

CodeMDD.io

How to Iterate Through a Dictionary in Python

Dictionaries are one of the most important and useful built-in data structures in Python. They’re everywhere and are a fundamental part of the language itself. In your code, you’ll use dictionaries to solve many programming problems that may require iterating through the dictionary at hand. In this tutorial, you’ll dive deep into how to iterate through a dictionary in Python.

Solid knowledge of dictionary iteration will help you write better, more robust code. In your journey through dictionary iteration, you’ll write several examples that will help you understand the different methods and techniques available.

Getting Started With Python Dictionaries

Before diving into dictionary iteration, let’s quickly review the basics of working with dictionaries in Python. A dictionary is a collection of key-value pairs enclosed in curly braces ({}) and separated by commas. Each key-value pair is separated by a colon (:). For example:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

Here, ‘name’, ‘age’, and ‘city’ are the keys, and ‘John’, 30, and ‘New York’ are the corresponding values.

Understanding How to Iterate Through a Dictionary in Python

There are various methods available to iterate through a dictionary in Python. In this tutorial, we’ll cover the following methods:

  1. Traversing a Dictionary Directly
  2. Looping Over Dictionary Items: The .items() Method
  3. Iterating Through Dictionary Keys: The .keys() Method
  4. Walking Through Dictionary Values: The .values() Method

Let’s go through each method in detail.

Traversing a Dictionary Directly

The simplest way to iterate through a dictionary is by directly accessing its keys. You can use a for loop to achieve this:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
for key in my_dict:
print(key, my_dict[key])

In this example, the loop iterates through the keys of my_dict and prints each key along with its corresponding value.

Looping Over Dictionary Items: The .items() Method

The .items() method returns a view object that contains key-value pairs as tuples. This allows you to iterate over both the keys and values of a dictionary simultaneously:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
for key, value in my_dict.items():
print(key, value)

The loop iterates through the items of my_dict and unpacks each tuple into the variables key and value. It then prints the key-value pairs.

Iterating Through Dictionary Keys: The .keys() Method

If you only need to iterate through the keys of a dictionary, you can use the .keys() method:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
for key in my_dict.keys():
print(key)

This loop iterates through the keys of my_dict and prints each key.

Walking Through Dictionary Values: The .values() Method

Similarly, if you only want to iterate through the values of a dictionary, you can use the .values() method:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
for value in my_dict.values():
print(value)

In this loop, my_dict.values() returns a view object containing the values of my_dict. The loop then iterates through these values and prints them.

Changing Dictionary Values During Iteration

Changing dictionary values while iterating can lead to unexpected behavior. To avoid this, it’s recommended to create a copy of the dictionary before iterating and modify the copy instead. Here’s an example:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
for key, value in my_dict.copy().items():
if value == 'New York':
my_dict[key] = 'San Francisco'
print(my_dict)

In this example, a copy of my_dict is created using the copy() method. Inside the loop, the value ‘New York’ is replaced with ‘San Francisco’ using the modified copy. The output will show the updated dictionary.

Safely Removing Items From a Dictionary During Iteration

Removing items from a dictionary while iterating can also cause unexpected results. To safely remove items, you can collect the keys to be removed in a separate list and then iterate over this list to remove the items one by one. Here’s an example:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
keys_to_remove = []
for key, value in my_dict.items():
if value == 'New York':
keys_to_remove.append(key)
for key in keys_to_remove:
del my_dict[key]
print(my_dict)

In this example, the keys to be removed are collected in the keys_to_remove list. Then, a second loop iterates over this list and removes the corresponding key-value pairs from my_dict. The output will show the dictionary without the removed items.

Iterating Through Dictionaries: for Loop Examples

Now, let’s explore some more advanced examples of iterating through dictionaries using a for loop.

Filtering Items by Their Value

You can filter items in a dictionary based on the values they hold. For example, let’s say we have a dictionary of ages, and we want to print the names of people who are under 30:

ages = {'John': 25, 'Alice': 35, 'Bob': 28, 'Emily': 22}
for name, age in ages.items():
if age < 30:
print(name)

The loop checks if the age is less than 30, and if it is, it prints the corresponding name.

Running Calculations With Keys and Values

You can perform calculations with both the keys and values of a dictionary. For instance, let’s calculate the sum of the ages in a dictionary:

ages = {'John': 25, 'Alice': 35, 'Bob': 28, 'Emily': 22}
total_age = 0
for age in ages.values():
total_age += age
print(total_age)

The loop iterates through the values of the dictionary and adds each age to the total_age variable. The output will display the sum of the ages.

Swapping Keys and Values Through Iteration

It’s also possible to swap the keys and values of a dictionary by iterating through it. Here’s an example:

original_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
swapped_dict = {value: key for key, value in original_dict.items()}
print(swapped_dict)

In this example, a dictionary comprehension is used to create a new dictionary, swapped_dict, where the keys of original_dict become the values, and the values become the keys. The output will show the swapped dictionary.

Iterating Through Dictionaries: Comprehension Examples

Dictionary comprehensions provide a concise and efficient way to create dictionaries. Let’s explore some examples of iterating through dictionaries using comprehensions.

Filtering Items by Their Value: Revisited

We can achieve the same result as the previous filtering example using a dictionary comprehension:

ages = {'John': 25, 'Alice': 35, 'Bob': 28, 'Emily': 22}
filtered_dict = {name: age for name, age in ages.items() if age < 30}
print(filtered_dict)

The comprehension iterates through the items of ages, filtering out the items with an age less than 30. The output will display the filtered dictionary.

Swapping Keys and Values Through Iteration: Revisited

We can also use a comprehension to swap the keys and values of a dictionary:

original_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
swapped_dict = {value: key for key, value in original_dict.items()}
print(swapped_dict)

In this example, the comprehension iterates through original_dict and creates a new dictionary, swapped_dict, with the keys and values swapped. The output will show the swapped dictionary.

Traversing a Dictionary in Sorted and Reverse Order

Python dictionaries are inherently unordered. However, you can traverse them in sorted or reverse order using some additional methods. Let’s explore these options.

Iterating Over Sorted Keys

You can iterate over the keys of a dictionary in sorted order using the sorted() function:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
for key in sorted(my_dict):
print(key)

In this example, the sorted() function sorts the keys of my_dict alphabetically and then iterates through them. The output will show the sorted keys.

Looping Through Sorted Values

Similarly, you can loop through the values of a dictionary in sorted order using the sorted() function:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
for value in sorted(my_dict.values()):
print(value)

Here, the sorted() function sorts the values of my_dict and then iterates through them. The output will display the sorted values.

Sorting a Dictionary With a Comprehension

If you want to sort a dictionary entirely based on its keys or values, you can use a comprehension in combination with the sorted() function. Here’s an example:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
sorted_dict = {key: my_dict[key] for key in sorted(my_dict)}
print(sorted_dict)

In this example, a dictionary comprehension is used to create a new dictionary, sorted_dict, where the keys are sorted alphabetically. The output will show the sorted dictionary.

Iterating Through a Dictionary in Reverse-Sorted Order

To iterate through a dictionary in reverse-sorted order, you can use the reversed() function in combination with the sorted() function:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
for key in reversed(sorted(my_dict)):
print(key)

In this example, the sorted() function sorts the keys of my_dict alphabetically, and the reversed() function reverses the order. The output will display the reverse-sorted keys.

Traversing a Dictionary in Reverse Order

If you simply want to traverse a dictionary in reverse order without sorting, you can use the .keys() method in combination with the reversed() function:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
for key in reversed(list(my_dict.keys())):
print(key)

Here, the .keys() method returns the keys of my_dict, which are then converted to a list. The reversed() function is used to reverse the order, and the loop iterates through the reversed keys. The output will display the keys in reverse order.

Iterating Over a Dictionary Destructively With .popitem()

The .popitem() method can be used to iteratively remove and return key-value pairs from a dictionary. This method removes the last added or last remaining key-value pair, depending on the dictionary’s implementation:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
while my_dict:
key, value = my_dict.popitem()
print(key, value)

In this example, the loop iteratively removes key-value pairs from my_dict using .popitem(), and then prints each pair. The loop continues until the dictionary becomes empty.

Using Built-in Functions to Implicitly Iterate Through Dictionaries

Python provides several built-in functions that allow you to implicitly iterate through dictionaries: map() and filter(). Let’s explore how to apply them to dictionary iteration.

Applying a Transformation to a Dictionary’s Items: map()

You can apply a transformation to a dictionary’s items using the map() function. For example, let’s convert the values of a dictionary to uppercase:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
uppercase_dict = {key: value.upper() for key, value in map(str, my_dict.items())}
print(uppercase_dict)

In this example, map(str, my_dict.items()) converts each item in my_dict to a string, value.upper() applies the uppercase transformation, and the resulting values are stored in uppercase_dict. The output will show the dictionary with uppercase values.

Filtering Items in a Dictionary: filter()

You can filter items in a dictionary using the filter() function. For instance, let’s keep only the items with names starting with ‘J’:

my_dict = {'John': 25, 'Alice': 35, 'Bob': 28, 'Emily': 22}
filtered_dict = {name: age for name, age in filter(lambda item: item[0].startswith('J'), my_dict.items())}
print(filtered_dict)

In this example, lambda item: item[0].startswith('J') defines a lambda function that checks if the name of each item starts with ‘J’. The items that pass the filter are stored in filtered_dict. The output will display the filtered dictionary.

Traversing Multiple Dictionaries as One

Python provides different ways to iterate through multiple dictionaries as if they were a single dictionary.

Iterating Through Multiple Dictionaries With ChainMap

The ChainMap class from the collections module allows you to traverse multiple dictionaries as one. Here’s an example:

from collections import ChainMap
dict1 = {'name': 'John', 'age': 30}
dict2 = {'city': 'New York', 'country': 'USA'}
combined_dict = ChainMap(dict1, dict2)
for key, value in combined_dict.items():
print(key, value)

In this example, the ChainMap class is used to combine dict1 and dict2 into a single combined_dict. The loop then iterates through the combined dictionary and prints each key-value pair. The output will show the combined dictionary.

Iterating Through a Chain of Dictionaries With chain()

The chain() function from the itertools module allows you to iterate through a chain of dictionaries as one. Here’s an example:

from itertools import chain
dict1 = {'name': 'John', 'age': 30}
dict2 = {'city': 'New York', 'country': 'USA'}
combined_dict = chain(dict1, dict2)
for key in combined_dict:
print(key)

In this example, the chain() function combines dict1 and dict2 into a single iterable combined_dict. The loop then iterates through the combined dictionary and prints each key. The output will show the keys in the combined dictionary.

Looping Over Merged Dictionaries: The Unpacking Operator (**)

You can merge dictionaries using the unpacking operator (**). This allows you to combine multiple dictionaries into one before or during iteration. Here’s an example:

dict1 = {'name': 'John', 'age': 30}
dict2 = {'city': 'New York', 'country': 'USA'}
dict3 = {'occupation': 'developer'}
combined_dict = {**dict1, **dict2, **dict3}
for key, value in combined_dict.items():
print(key, value)

In this example, the unpacking operator (**), together with curly braces, merges dict1, dict2, and dict3 into a single combined_dict. The loop then iterates through the combined dictionary and prints each key-value pair. The output will show the merged dictionary.

Key Takeaways

Iterating through dictionaries is a fundamental skill in Python programming. In this tutorial, you’ve learned several ways to iterate through a dictionary, including directly, by looping over items, keys, and values, and using comprehensions. You’ve also explored more advanced techniques, such as filtering items, running calculations, swapping keys and values, sorting, and reversing. Additionally, you’ve discovered how to iterate through multiple dictionaries and merge dictionaries using the unpacking operator. With this knowledge, you can efficiently iterate through dictionaries, solve programming problems, and write clean and robust code.

CodeMDD.io