Skip to content

Iterating Over a Python Dictionary Effortlessly

[

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 ways of traversing a dictionary in Python.

Getting Started With Python Dictionaries

Before diving into dictionary iteration, let’s do a quick review of Python dictionaries. Dictionaries are unordered collections of key-value pairs. Each key-value pair is separated by a colon (:), and the pairs themselves are separated by commas. Here’s an example of a dictionary:

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

In this example, "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

Python provides several methods and techniques for iterating through a dictionary. Let’s explore some of them:

Traversing a Dictionary Directly

One simple way to iterate through a dictionary is by using a for loop. The loop will iterate over the keys of the dictionary. Here’s an example:

my_dict = {"a": 1, "b": 2, "c": 3}
for key in my_dict:
print(key)

Output:

a
b
c

Looping Over Dictionary Items: The .items() Method

The .items() method allows you to iterate over both the keys and values of a dictionary simultaneously. It returns a list of tuples, where each tuple contains a key-value pair from the dictionary. Here’s an example:

my_dict = {"a": 1, "b": 2, "c": 3}
for key, value in my_dict.items():
print(key, value)

Output:

a 1
b 2
c 3

Iterating Through Dictionary Keys: The .keys() Method

The .keys() method returns a view object that contains the keys of a dictionary. You can iterate over this view object to access the keys. Here’s an example:

my_dict = {"a": 1, "b": 2, "c": 3}
for key in my_dict.keys():
print(key)

Output:

a
b
c

Walking Through Dictionary Values: The .values() Method

The .values() method returns a view object that contains the values of a dictionary. You can iterate over this view object to access the values. Here’s an example:

my_dict = {"a": 1, "b": 2, "c": 3}
for value in my_dict.values():
print(value)

Output:

1
2
3

Changing Dictionary Values During Iteration

If you need to modify the values of a dictionary while iterating over it, you should be cautious. Modifying a dictionary during iteration can lead to unexpected results or even runtime errors. To safely modify the values, you can create a copy of the dictionary and modify the copy. Here’s an example:

my_dict = {"a": 1, "b": 2, "c": 3}
new_dict = my_dict.copy()
for key, value in my_dict.items():
new_dict[key] = value * 2
print(new_dict)

Output:

{"a": 2, "b": 4, "c": 6}

Safely Removing Items From a Dictionary During Iteration

Similar to modifying a dictionary, removing items from a dictionary while iterating can cause problems. To safely remove items from a dictionary, you can use a separate list to store the keys of the items you want to remove, and then loop over the list to remove them. Here’s an example:

my_dict = {"a": 1, "b": 2, "c": 3}
keys_to_remove = []
for key, value in my_dict.items():
if value == 2:
keys_to_remove.append(key)
for key in keys_to_remove:
del my_dict[key]
print(my_dict)

Output:

{"a": 1, "c": 3}

Iterating Through Dictionaries: for Loop Examples

Let’s explore a few more examples of iterating through dictionaries using for loops:

Filtering Items by Their Value

You can filter dictionary items based on their values. Here’s an example that filters out items with values less than or equal to 2:

my_dict = {"a": 1, "b": 2, "c": 3}
for key, value in my_dict.items():
if value > 2:
print(key, value)

Output:

c 3

Running Calculations With Keys and Values

You can perform calculations using both the keys and values of a dictionary. Here’s an example that calculates the sum of the keys and values:

my_dict = {"a": 1, "b": 2, "c": 3}
key_sum = 0
value_sum = 0
for key, value in my_dict.items():
key_sum += key
value_sum += value
print(key_sum, value_sum)

Output:

6 6

Swapping Keys and Values Through Iteration

You can swap the keys and values of a dictionary by iterating through the items and creating a new dictionary with the swapped values. Here’s an example:

my_dict = {"a": 1, "b": 2, "c": 3}
swapped_dict = {}
for key, value in my_dict.items():
swapped_dict[value] = key
print(swapped_dict)

Output:

{1: "a", 2: "b", 3: "c"}

Iterating Through Dictionaries: Comprehension Examples

Python comprehensions provide concise ways to create dictionaries using iteration. Let’s explore a few examples:

Filtering Items by Their Value: Revisited

You can use a dictionary comprehension to filter out items by their values. Here’s the previous example using a comprehension:

my_dict = {"a": 1, "b": 2, "c": 3}
filtered_dict = {key: value for key, value in my_dict.items() if value > 2}
print(filtered_dict)

Output:

{"c": 3}

Swapping Keys and Values Through Iteration: Revisited

You can also use a dictionary comprehension to swap the keys and values of a dictionary. Here’s the previous example using a comprehension:

my_dict = {"a": 1, "b": 2, "c": 3}
swapped_dict = {value: key for key, value in my_dict.items()}
print(swapped_dict)

Output:

{1: "a", 2: "b", 3: "c"}

Traversing a Dictionary in Sorted and Reverse Order

You can also traverse a dictionary in different orders, such as sorted or reverse-sorted. Let’s explore a few methods:

Iterating Over Sorted Keys

To iterate over the keys of a dictionary in sorted order, you can use the sorted() function. Here’s an example:

my_dict = {"b": 2, "a": 1, "c": 3}
for key in sorted(my_dict):
print(key)

Output:

a
b
c

Looping Through Sorted Values

If you want to iterate through the values of a dictionary in sorted order, you can use the sorted() function together with the .values() method. Here’s an example:

my_dict = {"b": 2, "a": 1, "c": 3}
for value in sorted(my_dict.values()):
print(value)

Output:

1
2
3

Sorting a Dictionary With a Comprehension

To create a new dictionary with its keys sorted, you can use a dictionary comprehension together with the sorted() function. Here’s an example:

my_dict = {"b": 2, "a": 1, "c": 3}
sorted_dict = {key: my_dict[key] for key in sorted(my_dict)}
print(sorted_dict)

Output:

{"a": 1, "b": 2, "c": 3}

Iterating Through a Dictionary in Reverse-Sorted Order

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

my_dict = {"b": 2, "a": 1, "c": 3}
for key in reversed(sorted(my_dict)):
print(key)

Output:

c
b
a

Traversing a Dictionary in Reverse Order

To traverse a dictionary in reverse order, you can use the .reverse() method on a list of the dictionary keys. Here’s an example:

my_dict = {"b": 2, "a": 1, "c": 3}
for key in list(my_dict.keys())[::-1]:
print(key)

Output:

c
b
a

Iterating Over a Dictionary Destructively With .popitem()

The .popitem() method allows you to remove items from a dictionary while iterating over it. It removes and returns an arbitrary key-value pair from the dictionary. Here’s an example that prints the key-value pairs in reverse order:

my_dict = {"a": 1, "b": 2, "c": 3}
while my_dict:
key, value = my_dict.popitem()
print(key, value)

Output:

c 3
b 2
a 1

Using Built-in Functions to Implicitly Iterate Through Dictionaries

Python provides built-in functions, such as map() and filter(), that can be used to implicitly iterate through dictionaries. Let’s explore them:

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

The map() function allows you to transform the items of a dictionary using a mapping function. Here’s an example that doubles the values of a dictionary:

my_dict = {"a": 1, "b": 2, "c": 3}
new_dict = dict(map(lambda item: (item[0], item[1] * 2), my_dict.items()))
print(new_dict)

Output:

{"a": 2, "b": 4, "c": 6}

Filtering Items in a Dictionary: filter()

The filter() function allows you to filter the items of a dictionary using a filter function. Here’s an example that keeps only the items with values greater than 2:

my_dict = {"a": 1, "b": 2, "c": 3}
new_dict = dict(filter(lambda item: item[1] > 2, my_dict.items()))
print(new_dict)

Output:

{"c": 3}

Traversing Multiple Dictionaries as One

Sometimes you may have multiple dictionaries that you want to iterate through as if they were a single dictionary. Python provides a couple of methods to achieve this:

Iterating Through Multiple Dictionaries With ChainMap

The ChainMap class from the collections module can be used to combine multiple dictionaries into a single iterable. Here’s an example:

from collections import ChainMap
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
combined_dict = ChainMap(dict1, dict2)
for key, value in combined_dict.items():
print(key, value)

Output:

a 1
b 2
c 3
d 4

Iterating Through a Chain of Dictionaries With chain()

The chain() function from the itertools module can be used to combine multiple dictionaries into a single iterable. Here’s an example:

from itertools import chain
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
combined_dict = chain(dict1.items(), dict2.items())
for key, value in combined_dict:
print(key, value)

Output:

a 1
b 2
c 3
d 4

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

You can also merge multiple dictionaries into a single dictionary and loop over the merged dictionary using the unpacking operator (**). Here’s an example:

dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged_dict = {**dict1, **dict2}
for key, value in merged_dict.items():
print(key, value)

Output:

a 1
b 2
c 3
d 4

Key Takeaways

Iterating through dictionaries in Python is a fundamental skill that every Python programmer should have. It allows you to access and process the key-value pairs of a dictionary in various ways. In this tutorial, you learned several methods and techniques for iterating through dictionaries, including direct traversal, using the .items(), .keys(), and .values() methods, safely modifying and removing items, iterating in sorted and reverse order, using comprehensions and built-in functions, and traversing multiple dictionaries. Knowing these techniques will help you write better, more efficient code when working with dictionaries in Python.