Skip to content

Iterating through Python Dictionary

[

How to Iterate Through a Dictionary in Python

Dictionaries are a fundamental part of the Python programming language and are widely used for solving various programming problems. Understanding how to iterate through a dictionary is an essential skill that can help you write more efficient and robust code. In this tutorial, we will explore different methods for iterating through dictionaries in Python.

Getting Started With Python Dictionaries

Before we dive into dictionary iteration, let’s briefly review some basics about dictionaries in Python. A dictionary is an unordered collection of key-value pairs, where each key is unique. You can think of a dictionary as a set of labeled containers, where each container holds a specific value identified by its unique key.

In Python, dictionaries are defined using curly braces {} and key-value pairs separated by a colon :. Here is an example of a dictionary that stores the ages of three people:

ages = {
"Alice": 25,
"Bob": 30,
"Charlie": 35
}

To access the value associated with a specific key, you can use square brackets []. For example, to access Bob’s age, you would write ages["Bob"].

Now that we have a basic understanding of dictionaries, let’s explore different methods for iterating through them.

Traversing a Dictionary Directly

One way to iterate through a dictionary in Python is by using a for loop. This allows you to traverse each key in the dictionary and access its corresponding value. Here’s an example:

ages = {
"Alice": 25,
"Bob": 30,
"Charlie": 35
}
for key in ages:
print(key, ages[key])

Output:

Alice 25
Bob 30
Charlie 35

In this example, the for loop iterates over the dictionary ages and assigns each key to the variable key. We can then use key to access the corresponding value in the dictionary ages.

Looping Over Dictionary Items: The .items() Method

Another way to iterate through a dictionary is by using the .items() method. This method returns a view object that contains key-value pairs of the dictionary. You can then iterate over this view object to access both the keys and values. Here’s an example:

ages = {
"Alice": 25,
"Bob": 30,
"Charlie": 35
}
for key, value in ages.items():
print(key, value)

Output:

Alice 25
Bob 30
Charlie 35

In this example, the .items() method returns a view object that contains the key-value pairs of the ages dictionary. The for loop iterates over this view object and assigns each key to the variable key and each value to the variable value.

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. This method returns a view object that contains the keys of the dictionary. Here’s an example:

ages = {
"Alice": 25,
"Bob": 30,
"Charlie": 35
}
for key in ages.keys():
print(key)

Output:

Alice
Bob
Charlie

In this example, the .keys() method returns a view object that contains the keys of the ages dictionary. The for loop iterates over this view object and prints each key.

Walking Through Dictionary Values: The .values() Method

Similarly, if you only need to iterate through the values of a dictionary, you can use the .values() method. This method returns a view object that contains the values of the dictionary. Here’s an example:

ages = {
"Alice": 25,
"Bob": 30,
"Charlie": 35
}
for value in ages.values():
print(value)

Output:

25
30
35

In this example, the .values() method returns a view object that contains the values of the ages dictionary. The for loop iterates over this view object and prints each value.

Changing Dictionary Values During Iteration

It is important to note that modifying a dictionary’s values while iterating through it can lead to unexpected results. If you need to update the dictionary’s values, it is recommended to first create a copy of the dictionary and iterate through the copy. Here’s an example:

ages = {
"Alice": 25,
"Bob": 30,
"Charlie": 35
}
# Create a copy of the dictionary
ages_copy = ages.copy()
for key in ages_copy:
ages[key] += 1
print(ages)

Output:

{
"Alice": 26,
"Bob": 31,
"Charlie": 36
}

In this example, we create a copy of the ages dictionary using the copy() method. We then iterate through the copy and increment each value by 1. This ensures that the original dictionary remains unchanged while allowing us to modify the values during iteration.

Safely Removing Items From a Dictionary During Iteration

Similarly, removing items from a dictionary while iterating through it can also lead to unexpected results. To safely remove items from a dictionary, you can create a list of keys to remove and then iterate through this list to delete the corresponding items from the dictionary. Here’s an example:

ages = {
"Alice": 25,
"Bob": 30,
"Charlie": 35
}
keys_to_remove = []
for key, value in ages.items():
if value > 30:
keys_to_remove.append(key)
for key in keys_to_remove:
del ages[key]
print(ages)

Output:

{
"Alice": 25,
"Bob": 30
}

In this example, we iterate through the ages dictionary and append the keys of items with a value greater than 30 to the keys_to_remove list. We then iterate through the keys_to_remove list and delete the corresponding items from the ages dictionary. This ensures that we can remove items from the dictionary without modifying it during iteration.

Iterating Through Dictionaries: for Loop Examples

In addition to the methods discussed above, you can use for loops with conditional statements to perform various operations on dictionary items. Here are a few examples:

Filtering Items by Their Value

ages = {
"Alice": 25,
"Bob": 30,
"Charlie": 35
}
for key, value in ages.items():
if value > 30:
print(key, value)

Output:

Charlie 35

In this example, we iterate through the ages dictionary and use a conditional statement to filter items with a value greater than 30. We then print the keys and values of the filtered items.

Running Calculations With Keys and Values

ages = {
"Alice": 25,
"Bob": 30,
"Charlie": 35
}
total_age = 0
for key, value in ages.items():
total_age += value
print(total_age)

Output:

90

In this example, we iterate through the ages dictionary and use the values to calculate the total age. We initialize the total_age variable to 0 and add each value to it during each iteration.

Swapping Keys and Values Through Iteration

ages = {
"Alice": 25,
"Bob": 30,
"Charlie": 35
}
swapped_ages = {}
for key, value in ages.items():
swapped_ages[value] = key
print(swapped_ages)

Output:

{25: "Alice", 30: "Bob", 35: "Charlie"}

In this example, we iterate through the ages dictionary and create a new dictionary swapped_ages by swapping the keys and values. We assign each value as the key and each key as the value during each iteration.

Iterating Through Dictionaries: Comprehension Examples

Python comprehensions provide a concise way to create new dictionaries or perform operations on existing dictionaries in a single line of code. Here are a few examples of using comprehensions to iterate through dictionaries:

Filtering Items by Their Value: Revisited

ages = {
"Alice": 25,
"Bob": 30,
"Charlie": 35
}
filtered_ages = {key: value for key, value in ages.items() if value > 30}
print(filtered_ages)

Output:

{"Charlie": 35}

In this example, we use a dictionary comprehension to filter items with a value greater than 30. We iterate through the ages dictionary and only include items that satisfy the conditional statement in the new dictionary filtered_ages.

Swapping Keys and Values Through Iteration: Revisited

ages = {
"Alice": 25,
"Bob": 30,
"Charlie": 35
}
swapped_ages = {value: key for key, value in ages.items()}
print(swapped_ages)

Output:

{25: "Alice", 30: "Bob", 35: "Charlie"}

In this example, we use a dictionary comprehension to swap the keys and values of the ages dictionary. We iterate through the ages dictionary and assign each value as the key and each key as the value in the new dictionary swapped_ages.

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 various methods to achieve this.

Iterating Over Sorted Keys

ages = {
"Alice": 25,
"Bob": 30,
"Charlie": 35
}
for key in sorted(ages.keys()):
print(key)

Output:

Alice
Bob
Charlie

In this example, we use the sorted() function to sort the keys of the ages dictionary before iterating through them. This allows us to traverse the dictionary in ascending order of the keys.

Looping Through Sorted Values

ages = {
"Alice": 25,
"Bob": 30,
"Charlie": 35
}
for value in sorted(ages.values()):
print(value)

Output:

25
30
35

In this example, we use the sorted() function to sort the values of the ages dictionary before iterating through them. This allows us to traverse the dictionary in ascending order of the values.

Sorting a Dictionary With a Comprehension

ages = {
"Alice": 25,
"Bob": 30,
"Charlie": 35
}
sorted_ages = {key: value for key, value in sorted(ages.items())}
print(sorted_ages)

Output:

{"Alice": 25, "Bob": 30, "Charlie": 35}

In this example, we use a dictionary comprehension and the sorted() function to sort the dictionary ages by key. This creates a new dictionary sorted_ages where the keys are sorted in ascending order.

Iterating Through a Dictionary in Reverse-Sorted Order

ages = {
"Alice": 25,
"Bob": 30,
"Charlie": 35
}
for key in sorted(ages.keys(), reverse=True):
print(key)

Output:

Charlie
Bob
Alice

In this example, we use the sorted() function with the reverse=True argument to sort the keys of the ages dictionary in descending order before iterating through them. This allows us to traverse the dictionary in reverse-sorted order.

Traversing a Dictionary in Reverse Order

ages = {
"Alice": 25,
"Bob": 30,
"Charlie": 35
}
for key in reversed(list(ages.keys())):
print(key)

Output:

Charlie
Bob
Alice

In this example, we use the reversed() function to reverse the keys of the ages dictionary before iterating through them. We convert the keys to a list to ensure compatibility with the reversed() function.

Iterating Over a Dictionary Destructively With .popitem()

The .popitem() method allows you to remove and return an arbitrary key-value pair from a dictionary. This can be useful when you need to iterate over a dictionary and remove items one by one. Here’s an example:

ages = {
"Alice": 25,
"Bob": 30,
"Charlie": 35
}
while ages:
key, value = ages.popitem()
print(key, value)

Output:

Charlie 35
Bob 30
Alice 25

In this example, we use a while loop to repeatedly call the .popitem() method on the ages dictionary until it becomes empty. The method removes and returns an arbitrary key-value pair, which we then print.

Using Built-in Functions to Implicitly Iterate Through Dictionaries

Python provides two built-in functions, map() and filter(), that can be used to implicitly iterate through dictionaries and perform operations on their items.

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

The map() function applies a transformation function to each item in an iterable and returns an iterator over the transformed items. In the case of dictionaries, you can use map() to apply a transformation function to each key-value pair. Here’s an example:

ages = {
"Alice": 25,
"Bob": 30,
"Charlie": 35
}
def double_age(item):
key, value = item
return key, value * 2
doubled_ages = dict(map(double_age, ages.items()))
print(doubled_ages)

Output:

{"Alice": 50, "Bob": 60, "Charlie": 70}

In this example, we define a double_age() function that takes a key-value pair and returns a new key-value pair with the value doubled. We then use map() together with ages.items() to apply this function to each key-value pair in the dictionary. Finally, we convert the transformed items back into a dictionary using the dict() function.

Filtering Items in a Dictionary: filter()

The filter() function applies a filtering function to each item in an iterable and returns an iterator over the items that satisfy the filter. In the case of dictionaries, you can use filter() to keep only the items that satisfy a certain condition. Here’s an example:

ages = {
"Alice": 25,
"Bob": 30,
"Charlie": 35
}
def is_even_age(item):
key, value = item
return value % 2 == 0
even_ages = dict(filter(is_even_age, ages.items()))
print(even_ages)

Output:

{"Bob": 30}

In this example, we define an is_even_age() function that takes a key-value pair and returns True if the value is even, and False otherwise. We then use filter() together with ages.items() to keep only the key-value pairs that satisfy this condition. Finally, we convert the filtered items back into a dictionary using the dict() function.

Traversing Multiple Dictionaries as One

Sometimes, you may need to iterate through multiple dictionaries as if they were one combined dictionary. Python provides several methods for achieving this.

Iterating Through Multiple Dictionaries With ChainMap

The ChainMap class from the collections module allows you to combine multiple dictionaries and access their items as if they were one dictionary. Here’s an example:

from collections import ChainMap
ages1 = {
"Alice": 25,
"Bob": 30
}
ages2 = {
"Charlie": 35,
"Dave": 40
}
all_ages = ChainMap(ages1, ages2)
for key, value in all_ages.items():
print(key, value)

Output:

Alice 25
Bob 30
Charlie 35
Dave 40

In this example, we create two dictionaries ages1 and ages2. We then create a ChainMap object all_ages by passing in the dictionaries as arguments. This allows us to iterate over the combined items of ages1 and ages2 using the .items() method.

Iterating Through a Chain of Dictionaries With chain()

The chain() function from the itertools module allows you to combine multiple iterables into one iterable sequence. Here’s an example of using chain() to iterate through a chain of dictionaries:

from itertools import chain
ages1 = {
"Alice": 25,
"Bob": 30
}
ages2 = {
"Charlie": 35,
"Dave": 40
}
all_ages = chain(ages1.items(), ages2.items())
for key, value in all_ages:
print(key, value)

Output:

Alice 25
Bob 30
Charlie 35
Dave 40

In this example, we combine the items of ages1 and ages2 using the chain() function and iterate over the combined items using a for loop.

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

In Python 3.9 and later versions, you can merge dictionaries using the unpacking operator **, which allows you to create a new dictionary that combines the key-value pairs of multiple dictionaries. Here’s an example:

ages1 = {
"Alice": 25,
"Bob": 30
}
ages2 = {
"Charlie": 35,
"Dave": 40
}
all_ages = {**ages1, **ages2}
for key, value in all_ages.items():
print(key, value)

Output:

Alice 25
Bob 30
Charlie 35
Dave 40

In this example, we merge the dictionaries ages1 and ages2 using the unpacking operator **. This creates a new dictionary all_ages that contains the combined key-value pairs. We can then iterate over the items of all_ages using the .items() method.

Key Takeaways

Iterating through dictionaries in Python is an essential skill that can help you write more efficient and effective code. In this tutorial, we explored various methods for iterating through dictionaries, including using for loops, the .items(), .keys(), and .values() methods, dictionary comprehensions, and built-in functions like map() and filter(). We also learned techniques for modifying a dictionary during iteration, safely removing items, and traversing dictionaries in sorted and reverse order. Additionally, we discussed how to loop over multiple dictionaries as one using ChainMap, chain(), and the unpacking operator **. These techniques will empower you to leverage the full potential of dictionaries in your Python programming journey.