Skip to content

Python Iterating Dictionary Effortlessly

CodeMDD.io

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 grasp the concepts and become proficient in iterating through dictionaries.

Getting Started With Python Dictionaries

Before diving into dictionary iteration, let’s quickly review the basics of Python dictionaries. A dictionary is an unordered collection of key-value pairs, where each key is unique. They are defined using curly braces {} and the key-value pairs are separated by a colon :. For example:

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

There are several ways to iterate through a dictionary in Python, depending on what you want to iterate over (keys, values, or key-value pairs). Let’s explore each method in detail.

Traversing a Dictionary Directly

You can directly traverse a dictionary using a for loop. In this case, the loop variable takes the values of the dictionary’s keys. Here’s an example:

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

Output:

name
age
city

In this example, the loop prints the keys ("name", "age", and "city") one by one.

Looping Over Dictionary Items: The .items() Method

If you want to iterate over both keys and values, you can use the .items() method. This method returns a view object that contains tuples of key-value pairs. Here’s an example:

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

Output:

name John
age 30
city New York

In this example, the loop prints both the keys and their corresponding values.

Iterating Through Dictionary Keys: The .keys() Method

If you are only interested in iterating over 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:

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

Output:

name
age
city

In this example, the loop only prints the keys of the dictionary.

Walking Through Dictionary Values: The .values() Method

If you only need to iterate over 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:

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

Output:

John
30
New York

In this example, the loop only prints the values of the dictionary.

Changing Dictionary Values During Iteration

Sometimes, you may need to change the values of a dictionary while iterating through it. However, it’s important to note that changing the size of a dictionary during iteration can lead to unexpected results or errors. To overcome this issue, you can create a copy of the dictionary or use the .copy() method. Here’s an example:

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

Output:

{'name': 'John', 'age': 31, 'city': 'New York'}

In this example, we check if the value is equal to 30, and if so, we update it to 31 using the key. By creating a copy of the dictionary, we avoid modifying the dictionary size during iteration.

Safely Removing Items From a Dictionary During Iteration

Similarly to changing values during iteration, removing items from a dictionary may lead to unexpected results or errors. To safely remove items, you can create a copy of the dictionary or use the .copy() method. Here’s an example:

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

Output:

{'name': 'John', 'city': 'New York'}

In this example, we check if the value is equal to 30, and if so, we delete the item using the key. By creating a copy of the dictionary, we avoid modifying the dictionary size during iteration.

Iterating Through Dictionaries: for Loop Examples

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

Filtering Items by Their Value

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

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

Output:

apple 4
pear 3

In this example, we filter the dictionary items and only print the key-value pairs where the value is greater than 2.

Running Calculations With Keys and Values

You can use a for loop to perform calculations using the keys and values of a dictionary. Here’s an example:

sales = {
"apple": 4,
"banana": 2,
"pear": 3,
"orange": 1
}
total = 0
for key, value in sales.items():
sales[key] *= 2
total += value
print(sales)
print(total)

Output:

{'apple': 8, 'banana': 4, 'pear': 6, 'orange': 2}
10

In this example, we double the values of the dictionary items and calculate the total value by summing the original values.

Swapping Keys and Values Through Iteration

You can use a for loop to swap the keys and values of a dictionary. Here’s an example:

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

Output:

{'apple': 1, 'banana': 2, 'pear': 3, 'orange': 4}

In this example, we iterate through the dictionary items and create a new dictionary where the keys become the values and the values become the keys.

Iterating Through Dictionaries: Comprehension Examples

Python comprehensions provide a concise way to create dictionaries while iterating over another dictionary. Let’s explore some examples of comprehensions for dictionary iteration.

Filtering Items by Their Value: Revisited

We can use a dictionary comprehension to filter items based on their value. Here’s an example:

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

Output:

{'apple': 4, 'pear': 3}

In this example, we create a new dictionary that includes only the key-value pairs where the value is greater than 2.

Swapping Keys and Values Through Iteration: Revisited

We can use a dictionary comprehension to swap the keys and values of a dictionary. Here’s an example:

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

Output:

{4: 'apple', 2: 'banana', 3: 'pear', 1: 'orange'}

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

Traversing a Dictionary in Sorted and Reverse Order

By default, dictionaries are unordered collections. However, if you need to traverse a dictionary in a specific order, you can sort it using different approaches.

Iterating Over Sorted Keys

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

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

Output:

apple 4
banana 2
orange 1
pear 3

In this example, the dictionary keys are sorted in alphabetical order, and the corresponding values are printed.

Looping Through Sorted Values

If you need to traverse a dictionary in sorted order based on its values, you can use the sorted() function with the key parameter. Here’s an example:

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

Output:

orange 1
banana 2
pear 3
apple 4

In this example, the dictionary items are sorted based on their values, and the key-value pairs are printed.

Sorting a Dictionary with a Comprehension

You can also use a dictionary comprehension to create a new dictionary with the items sorted based on either keys or values. Here’s an example:

my_dict = {
"banana": 2,
"apple": 4,
"orange": 1,
"pear": 3
}
sorted_dict = {key: my_dict[key] for key in sorted(my_dict.keys())}
print(sorted_dict)

Output:

{'apple': 4, 'banana': 2, 'orange': 1, 'pear': 3}

In this example, a new dictionary is created with the items sorted based on the keys.

Iterating Through a Dictionary in Reverse-Sorted Order

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

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

Output:

pear 3
orange 1
banana 2
apple 4

In this example, the dictionary keys are sorted in reverse order, and the corresponding values are printed.

Traversing a Dictionary in Reverse Order

To traverse a dictionary in reverse order, you can use the .items() method with the reversed() function. Here’s an example:

my_dict = {
"banana": 2,
"apple": 4,
"orange": 1,
"pear": 3
}
for key, value in reversed(list(my_dict.items())):
print(key, value)

Output:

pear 3
orange 1
banana 2
apple 4

In this example, the dictionary items are printed in reverse order.

Iterating Over a Dictionary Destructively With .popitem()

If you need to iterate over a dictionary and remove items from it, you can use the .popitem() method. This method removes and returns the last inserted item from the dictionary. Here’s an example:

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

Output:

orange 1
pear 3
banana 2
apple 4

In this example, the dictionary items are printed in reverse order as the .popitem() method removes the last inserted item in each iteration.

Using Built-in Functions to Implicitly Iterate Through Dictionaries

Python provides built-in functions that allow you to implicitly iterate through dictionaries and perform operations on their items.

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

The map() function can be used to apply a transformation to a dictionary’s items using a function or lambda expression. Here’s an example:

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

Output:

{'apple': 8, 'banana': 4, 'pear': 6, 'orange': 2}

In this example, we double the values of the dictionary items using map() and a lambda expression.

Filtering Items in a Dictionary: filter()

The filter() function can be used to filter items in a dictionary based on a condition defined by a function or lambda expression. Here’s an example:

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

Output:

{'apple': 4, 'pear': 3}

In this example, we filter the dictionary items based on the condition that the value is greater than 2 using filter() and a lambda expression.

Traversing Multiple Dictionaries as One

Python provides ways to traverse multiple dictionaries as if they were one. Let’s explore two approaches: ChainMap and chain().

Iterating Through Multiple Dictionaries With ChainMap

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

from collections import ChainMap
dict1 = {
"apple": 4,
"banana": 2
}
dict2 = {
"pear": 3,
"orange": 1
}
combined_dict = ChainMap(dict1, dict2)
for key, value in combined_dict.items():
print(key, value)

Output:

apple 4
banana 2
pear 3
orange 1

In this example, dict1 and dict2 are combined using ChainMap, and the resulting dictionary is iterated over.

Iterating Through a Chain of Dictionaries With chain()

The chain() function from the itertools module can be used to iterate through multiple dictionaries one after another. Here’s an example:

from itertools import chain
dict1 = {
"apple": 4,
"banana": 2
}
dict2 = {
"pear": 3,
"orange": 1
}
for key, value in chain(dict1.items(), dict2.items()):
print(key, value)

Output:

apple 4
banana 2
pear 3
orange 1

In this example, the items of dict1 and dict2 are combined using chain(), and the resulting sequence is iterated over.

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

If you have multiple dictionaries that you want to iterate over as one, you can merge them into a single dictionary and iterate over that. The unpacking operator (**) can be used to merge dictionaries. Here’s an example:

dict1 = {
"apple": 4,
"banana": 2
}
dict2 = {
"pear": 3,
"orange": 1
}
merged_dict = {**dict1, **dict2}
for key, value in merged_dict.items():
print(key, value)

Output:

apple 4
banana 2
pear 3
orange 1

In this example, dict1 and dict2 are merged using the unpacking operator, creating a new dictionary that can be iterated over.

Key Takeaways

Now you have a solid understanding of how to iterate through a dictionary in Python. You have learned various methods, including traversing a dictionary directly, looping over dictionary items using the .items() method, iterating through dictionary keys using the .keys() method, and walking through dictionary values using the .values() method.

You have also learned about changing dictionary values during iteration, safely removing items from a dictionary, and iterating through dictionaries using for loops, dictionary comprehensions, and built-in functions like map() and filter().

Additionally, you have explored how to traverse dictionaries in sorted and reverse order, iterate over dictionaries destructively using .popitem(), and iterate through multiple dictionaries as one using ChainMap, chain(), and the unpacking operator (**).

With this knowledge, you’ll be able to write more efficient and effective Python code that involves dictionary iteration.

CodeMDD.io