Skip to content

Iterating through a Python Dictionary Explained

CodeMDD.io

How to Iterate Through a Dictionary in Python

Dictionaries are a fundamental data structure in Python and are commonly used to store key-value pairs. When working with dictionaries, it is often necessary to iterate through the elements in order to perform various operations. In this tutorial, we will explore different methods for iterating through a dictionary in Python.

Getting Started With Python Dictionaries

Before we dive into iterating through dictionaries, let’s briefly cover the basics of working with dictionaries in Python.

To create a dictionary, you can use a pair of curly braces {} and separate the keys and values with a colon (:). For example:

my_dict = {'apple': 1, 'banana': 2, 'cherry': 3}

You can access the values in a dictionary by using the corresponding keys. For example:

print(my_dict['apple']) # Output: 1

Understanding How to Iterate Through a Dictionary in Python

There are several ways to iterate through a dictionary in Python. We will explore each method in detail below.

Traversing a Dictionary Directly

One way to iterate through a dictionary is by using a for loop and traversing the dictionary directly. This allows you to access both the keys and values of each element. Here’s an example:

my_dict = {'apple': 1, 'banana': 2, 'cherry': 3}
for key in my_dict:
print(key, my_dict[key])

Output:

apple 1
banana 2
cherry 3

Looping Over Dictionary Items: The .items() Method

The .items() method returns a view object that contains the key-value pairs of the dictionary. This allows you to iterate through both the keys and values together. Here’s an example:

my_dict = {'apple': 1, 'banana': 2, 'cherry': 3}
for key, value in my_dict.items():
print(key, value)

Output:

apple 1
banana 2
cherry 3

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:

my_dict = {'apple': 1, 'banana': 2, 'cherry': 3}
for key in my_dict.keys():
print(key)

Output:

apple
banana
cherry

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:

my_dict = {'apple': 1, 'banana': 2, 'cherry': 3}
for value in my_dict.values():
print(value)

Output:

1
2
3

Changing Dictionary Values During Iteration

It is important to note that you can modify dictionary values during iteration. However, if you try to add or remove dictionary items while iterating, it may result in unpredictable behavior. To safely update dictionary values, it is recommended to create a copy of the dictionary before iterating. Here’s an example:

my_dict = {'apple': 1, 'banana': 2, 'cherry': 3}
copy_dict = my_dict.copy()
for key in copy_dict:
copy_dict[key] += 1
print(copy_dict)

Output:

{'apple': 2, 'banana': 3, 'cherry': 4}

Safely Removing Items From a Dictionary During Iteration

To safely remove items from a dictionary during iteration, you can create a list of keys to remove and then iterate over that list. Here’s an example:

my_dict = {'apple': 1, 'banana': 2, 'cherry': 3}
keys_to_remove = []
for key in my_dict:
if my_dict[key] > 2:
keys_to_remove.append(key)
for key in keys_to_remove:
del my_dict[key]
print(my_dict)

Output:

{'apple': 1, 'banana': 2}

Iterating Through Dictionaries: for Loop Examples

In addition to the methods discussed above, you can use for loops to perform specific operations on dictionary elements.

Filtering Items by Their Value

You can filter items in a dictionary based on their values by using a for loop and an if statement. Here’s an example:

my_dict = {'apple': 1, 'banana': 2, 'cherry': 3}
for key in my_dict:
if my_dict[key] > 1:
print(key, my_dict[key])

Output:

banana 2
cherry 3

Running Calculations With Keys and Values

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

my_dict = {'apple': 1, 'banana': 2, 'cherry': 3}
total = 0
for key in my_dict:
total += my_dict[key]
print(total) # Output: 6

Swapping Keys and Values Through Iteration

In some cases, you may need to swap the keys and values of a dictionary. You can do this by using a for loop to iterate through the dictionary and create a new dictionary with the swapped keys and values. Here’s an example:

my_dict = {'apple': 1, 'banana': 2, 'cherry': 3}
swapped_dict = {}
for key in my_dict:
value = my_dict[key]
swapped_dict[value] = key
print(swapped_dict)

Output:

{1: 'apple', 2: 'banana', 3: 'cherry'}

##Iterating Through Dictionaries: Comprehension Examples

List comprehensions and dictionary comprehensions provide a compact and efficient way to iterate through dictionaries and perform operations.

Filtering Items by Their Value: Revisited

Using a dictionary comprehension, you can filter items in a dictionary based on their values in a concise manner. Here’s an example:

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

Output:

{'banana': 2, 'cherry': 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 an example:

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

Output:

{1: 'apple', 2: 'banana', 3: 'cherry'}

Traversing a Dictionary in Sorted and Reverse Order

By default, dictionaries do not maintain a specific order. However, you can traverse a dictionary in sorted and reverse order using the sorted() function.

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 = {'apple': 1, 'banana': 2, 'cherry': 3}
for key in sorted(my_dict.keys()):
print(key, my_dict[key])

Output:

apple 1
banana 2
cherry 3

Looping Through Sorted Values

Similarly, you can iterate through the values of a dictionary in sorted order. Here’s an example:

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

Output:

1
2
3

Sorting a Dictionary With a Comprehension

You can also use a dictionary comprehension to create a new dictionary with the elements sorted by either their keys or values. Here’s an example that sorts the dictionary by keys:

my_dict = {'apple': 1, 'banana': 2, 'cherry': 3}
sorted_dict = {key: my_dict[key] for key in sorted(my_dict.keys())}
print(sorted_dict)

Output:

{'apple': 1, 'banana': 2, 'cherry': 3}

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': 1, 'banana': 2, 'cherry': 3}
for key in reversed(sorted(my_dict.keys())):
print(key, my_dict[key])

Output:

cherry 3
banana 2
apple 1

Traversing a Dictionary in Reverse Order

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

my_dict = {'apple': 1, 'banana': 2, 'cherry': 3}
for key in reversed(my_dict):
print(key, my_dict[key])

Output:

cherry 3
banana 2
apple 1

Iterating Over a Dictionary Destructively With .popitem()

The .popitem() method allows you to iteratively remove and return an arbitrary (key, value) pair from a dictionary. This method is useful when you want to process dictionary elements in a specific order and remove them as you go. Here’s an example:

my_dict = {'apple': 1, 'banana': 2, 'cherry': 3}
while my_dict:
key, value = my_dict.popitem()
print(key, value)

Output:

cherry 3
banana 2
apple 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.

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

The map() function applies a given function to each item in an iterable and returns an iterator of the results. You can use map() to apply a transformation to the items of a dictionary. Here’s an example that doubles the values of a dictionary:

my_dict = {'apple': 1, 'banana': 2, 'cherry': 3}
doubled_dict = {key: value * 2 for key, value in map(lambda x: (x[0], x[1] * 2), my_dict.items())}
print(doubled_dict)

Output:

{'apple': 2, 'banana': 4, 'cherry': 6}

Filtering Items in a Dictionary: filter()

The filter() function returns an iterator that contains the items from an iterable for which a given function returns True. You can use filter() to filter items in a dictionary based on a specific condition. Here’s an example that filters out the items with odd values:

my_dict = {'apple': 1, 'banana': 2, 'cherry': 3}
filtered_dict = {key: value for key, value in filter(lambda x: x[1] % 2 == 0, my_dict.items())}
print(filtered_dict)

Output:

{'banana': 2}

Traversing Multiple Dictionaries as One

Sometimes, you may need to iterate through multiple dictionaries as if they were a single entity. Python provides two methods for achieving this: ChainMap and chain().

Iterating Through Multiple Dictionaries With ChainMap

The ChainMap class combines multiple dictionaries into a single dictionary-like object. You can iterate through the combined dictionaries using the items() method. Here’s an example:

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

Output:

apple 1
banana 2
cherry 3
date 4

Iterating Through a Chain of Dictionaries With chain()

The chain() function from the itertools module allows you to iterate through multiple dictionaries sequentially, without combining them into a single dictionary-like object. Here’s an example:

from itertools import chain
dict1 = {'apple': 1, 'banana': 2}
dict2 = {'cherry': 3, 'date': 4}
combined_dict = chain(dict1.items(), dict2.items())
for key, value in combined_dict:
print(key, value)

Output:

apple 1
banana 2
cherry 3
date 4

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

In Python 3.5 and later versions, you can use the unpacking operator ** to merge dictionaries and iterate over their items in a single loop. Here’s an example:

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

Output:

apple 1
banana 2
cherry 3
date 4

Key Takeaways

Iterating through a dictionary in Python is a common task when working with key-value data. In this tutorial, we explored various methods for iterating through dictionaries, including traversing the dictionary directly, using the .items(), .keys(), and .values() methods, and employing comprehensions and built-in functions. We also covered techniques for sorting dictionaries, removing items during iteration, and merging dictionaries. With a solid understanding of dictionary iteration, you can write more efficient and robust code in Python.