Skip to content

Effortlessly Iterate Python Dictionary

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 are everywhere and a fundamental part of the language itself. In your code, you will use dictionaries to solve many programming problems that may require iterating through the dictionary at hand. In this tutorial, we will dive deep into how to iterate through a dictionary in Python.

Getting Started With Python Dictionaries

Before we begin iterating through a dictionary, let’s first understand the basics of working with dictionaries in Python. A dictionary is an unordered collection of key-value pairs, where each key must be unique. You can think of it as a mapping between keys and values.

Here’s an example of a dictionary:

my_dict = {
"name": "John",
"age": 25,
"country": "USA"
}

In this example, “name”, “age”, and “country” are the keys, and “John”, 25, and “USA” are the values associated with those keys, respectively.

Understanding How to Iterate Through a Dictionary in Python

Now that we have a basic understanding of dictionaries, let’s explore the different ways to iterate through them.

Traversing a Dictionary Directly

The simplest way to iterate through a dictionary is by directly traversing it. This means accessing each key-value pair in the dictionary using a loop. Here’s an example:

my_dict = {
"name": "John",
"age": 25,
"country": "USA"
}
for key in my_dict:
value = my_dict[key]
print(key, value)

In this example, we use a for loop to iterate over the keys in the dictionary. We then access the corresponding value using the key and print both the key and value.

Looping Over Dictionary Items: The .items() Method

A more pythonic way to iterate through a dictionary is by using the .items() method. This method returns a view object that contains the key-value pairs of the dictionary. Here’s an example:

my_dict = {
"name": "John",
"age": 25,
"country": "USA"
}
for key, value in my_dict.items():
print(key, value)

In this example, we use a for loop and the .items() method to access both the key and value of each item in the dictionary. This is a more concise and preferred way to iterate through a dictionary in Python.

Iterating Through Dictionary Keys: The .keys() Method

Sometimes, you may only need to iterate through the keys of a dictionary without accessing their corresponding values. In such cases, you can use the .keys() method, which returns a view object containing the keys of the dictionary. Here’s an example:

my_dict = {
"name": "John",
"age": 25,
"country": "USA"
}
for key in my_dict.keys():
print(key)

In this example, we use a for loop and the .keys() method to iterate through the keys of the dictionary and print each key.

Walking Through Dictionary Values: The .values() Method

Similarly, if you are only interested in iterating through the values of a dictionary, you can use the .values() method. This method returns a view object containing the values of the dictionary. Here’s an example:

my_dict = {
"name": "John",
"age": 25,
"country": "USA"
}
for value in my_dict.values():
print(value)

In this example, we use a for loop and the .values() method to iterate through the values of the dictionary and print each value.

Changing Dictionary Values During Iteration

When iterating through a dictionary, you may want to modify the values of certain items. However, if you try to do this directly, you will encounter the “dictionary changed size during iteration” error. To avoid this error, you can create a copy of the dictionary and modify the original dictionary.

Here’s an example:

my_dict = {
"name": "John",
"age": 25,
"country": "USA"
}
for key in list(my_dict.keys()):
if key == "age":
my_dict[key] += 1
print(my_dict)

In this example, we create a copy of the dictionary using the list() constructor and iterate over the keys of the copied dictionary. If the key is “age”, we increment its value by 1. By using a copy of the dictionary, we can modify its values without causing any errors during iteration.

Safely Removing Items From a Dictionary During Iteration

Similar to changing values, removing items from a dictionary directly during iteration can cause the “dictionary changed size during iteration” error. To safely remove items from a dictionary, you can use the .items() method along with the list() constructor.

Here’s an example:

my_dict = {
"name": "John",
"age": 25,
"country": "USA"
}
for key, value in list(my_dict.items()):
if value == "USA":
del my_dict[key]
print(my_dict)

In this example, we iterate over the key-value pairs of a copied dictionary. If the value is “USA”, we remove the corresponding item from the original dictionary. Again, by using a copy of the dictionary, we can safely remove items without encountering any errors during iteration.

Iterating Through Dictionaries: for Loop Examples

Now that we have covered the basics of iterating through dictionaries, let’s explore some examples using the for loop.

Filtering Items by Their Value

You can use the for loop to filter items in a dictionary based on their values. Here’s an example:

my_dict = {
"apple": 2,
"banana": 4,
"cherry": 2,
"orange": 3
}
for key, value in my_dict.items():
if value > 2:
print(key)

In this example, we iterate over the key-value pairs of the dictionary and print the key if the corresponding value is greater than 2.

Running Calculations With Keys and Values

You can also perform calculations using the keys and values of a dictionary while iterating. Here’s an example:

my_dict = {
"apple": 2,
"banana": 4,
"cherry": 2,
"orange": 3
}
total = 0
for key, value in my_dict.items():
total += value
print(total)

In this example, we iterate over the items of the dictionary and calculate the total by adding up all the values.

Swapping Keys and Values Through Iteration

You can swap the keys and values of a dictionary by iterating through it. Here’s an example:

my_dict = {
"apple": 2,
"banana": 4,
"cherry": 2,
"orange": 3
}
new_dict = {}
for key, value in my_dict.items():
new_dict[value] = key
print(new_dict)

In this example, we iterate over the items of the dictionary and assign the keys as values and values as keys in a new dictionary.

Iterating Through Dictionaries: Comprehension Examples

Python comprehensions provide a concise way to create new dictionaries by iterating through existing ones. Let’s explore some examples using dictionary comprehensions.

Filtering Items by Their Value: Revisited

You can use dictionary comprehensions to filter items in a dictionary based on their values. Here’s an example:

my_dict = {
"apple": 2,
"banana": 4,
"cherry": 2,
"orange": 3
}
filtered_dict = {key: value for key, value in my_dict.items() if value > 2}
print(filtered_dict)

In this example, we create a new dictionary that only contains items from the original dictionary with values greater than 2.

Swapping Keys and Values Through Iteration: Revisited

Similarly, you can use dictionary comprehensions to swap the keys and values of a dictionary. Here’s an example:

my_dict = {
"apple": 2,
"banana": 4,
"cherry": 2,
"orange": 3
}
swapped_dict = {value: key for key, value in my_dict.items()}
print(swapped_dict)

In this example, we create a new dictionary where the keys and values are swapped from the original dictionary.

Traversing a Dictionary in Sorted and Reverse Order

By default, dictionaries in Python are unordered. However, if you need to iterate through a dictionary in a specific order, you can use the sorted() function, which returns a sorted list of keys.

Iterating Over Sorted Keys

Here’s an example of how to iterate over a dictionary in sorted order:

my_dict = {
"apple": 2,
"banana": 4,
"cherry": 2,
"orange": 3
}
for key in sorted(my_dict.keys()):
print(key)

In this example, we use the sorted() function to sort the keys of the dictionary and then iterate over them.

Looping Through Sorted Values

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

my_dict = {
"apple": 2,
"banana": 4,
"cherry": 2,
"orange": 3
}
for value in sorted(my_dict.values()):
print(value)

In this example, we sort the values of the dictionary and then loop through them.

Sorting a Dictionary With a Comprehension

You can also sort a dictionary using a comprehension. Here’s an example:

my_dict = {
"apple": 2,
"banana": 4,
"cherry": 2,
"orange": 3
}
sorted_dict = {key: value for key, value in sorted(my_dict.items(), key=lambda item: item[1])}
print(sorted_dict)

In this example, we use the sorted() function along with a lambda function to sort the dictionary based on its values. We then create a new dictionary using a comprehension.

Iterating Through a Dictionary in Reverse-Sorted Order

To iterate through a dictionary in reverse-sorted order, you can use the reversed() function along with the sorted() function. Here’s an example:

my_dict = {
"apple": 2,
"banana": 4,
"cherry": 2,
"orange": 3
}
for key in reversed(sorted(my_dict.keys())):
print(key)

In this example, we first sort the keys of the dictionary in ascending order using the sorted() function. Then, we use the reversed() function to iterate through them in reverse order.

Traversing a Dictionary in Reverse Order

If you simply want to traverse a dictionary in reverse order, you can use the reversed() function directly on the dictionary. Here’s an example:

my_dict = {
"apple": 2,
"banana": 4,
"cherry": 2,
"orange": 3
}
for key in reversed(my_dict):
print(key)

In this example, we use the reversed() function directly on the dictionary to traverse its keys in reverse order.

Iterating Over a Dictionary Destructively With .popitem()

The .popitem() method allows you to iteratively remove items from a dictionary while iterating over it. Here’s an example:

my_dict = {
"apple": 2,
"banana": 4,
"cherry": 2,
"orange": 3
}
while my_dict:
key, value = my_dict.popitem()
print(key, value)

In this example, we use a while loop to iterate over the dictionary while it is not empty. In each iteration, we remove the last item from the dictionary using the .popitem() method and print both the key and value.

Using Built-in Functions to Implicitly Iterate Through Dictionaries

Python provides built-in functions like map() and filter() that allow you to implicitly iterate through a dictionary without using a loop.

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

You can use the map() function to apply a transformation to the items of a dictionary. Here’s an example:

my_dict = {
"apple": 2,
"banana": 4,
"cherry": 2,
"orange": 3
}
new_dict = dict(map(lambda item: (item[0], item[1] + 1), my_dict.items()))
print(new_dict)

In this example, we use the map() function along with a lambda function to increment the value of each item in the dictionary by 1. We then convert the result into a new dictionary using the dict() constructor.

Filtering Items in a Dictionary: filter()

You can use the filter() function to filter items in a dictionary based on a condition. Here’s an example:

my_dict = {
"apple": 2,
"banana": 4,
"cherry": 2,
"orange": 3
}
filtered_dict = dict(filter(lambda item: item[1] > 2, my_dict.items()))
print(filtered_dict)

In this example, we use the filter() function along with a lambda function to keep only items from the original dictionary with values greater than 2. We then create a new dictionary using the dict() constructor.

Traversing Multiple Dictionaries as One

Python provides a few ways to traverse multiple dictionaries as if they were a single dictionary.

Iterating Through Multiple Dictionaries With ChainMap

You can use the ChainMap class from the collections module to create a view of multiple dictionaries as a single dictionary. Here’s an example:

from collections import ChainMap
dict1 = {"apple": 2, "banana": 4}
dict2 = {"cherry": 2, "orange": 3}
combined_dict = ChainMap(dict1, dict2)
for key in combined_dict:
print(key, combined_dict[key])

In this example, we use the ChainMap class to combine two dictionaries, dict1 and dict2, into a single dictionary called combined_dict. We then iterate over the keys of the combined dictionary and print both the key and value.

Iterating Through a Chain of Dictionaries With chain()

The chain() function from the itertools module allows you to iterate through multiple dictionaries in sequence. Here’s an example:

from itertools import chain
dict1 = {"apple": 2, "banana": 4}
dict2 = {"cherry": 2, "orange": 3}
combined_dict = chain(dict1, dict2)
for key in combined_dict:
print(key)

In this example, we use the chain() function to combine two dictionaries, dict1 and dict2, into an iterable called combined_dict. We then iterate over the keys of the combined iterable and print each key.

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

Python 3.5 introduced a new feature called the unpacking operator (**), which allows you to easily merge multiple dictionaries into a single dictionary. Here’s an example:

dict1 = {"apple": 2, "banana": 4}
dict2 = {"cherry": 2, "orange": 3}
merged_dict = {**dict1, **dict2}
for key in merged_dict:
print(key, merged_dict[key])

In this example, we use the unpacking operator (**), along with curly braces ({}) to merge the dictionaries dict1 and dict2 into a single dictionary called merged_dict. We then iterate over the keys of the merged dictionary and print both the key and value.

Key Takeaways

In this tutorial, you learned different ways to iterate through a dictionary in Python. You explored traversing a dictionary directly, using the .items(), .keys(), and .values() methods, changing dictionary values during iteration, safely removing items from a dictionary during iteration, using for loop with examples, using comprehension with examples, traversing a dictionary in sorted and reverse order, iterating over a dictionary destructively with .popitem(), using built-in functions to implicitly iterate through dictionaries, traversing multiple dictionaries as one with ChainMap and chain(), and looping over merged dictionaries using the unpacking operator (**). These skills will help you write better and more efficient code when working with dictionaries in Python.