Skip to content

Effortlessly Iterate Through 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’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 different techniques to traverse dictionaries effectively.

Getting Started With Python Dictionaries

Before diving into dictionary iteration, it is essential to have a basic understanding of Python dictionaries. Dictionaries are unordered collections of key-value pairs. You can think of them as a set of keys, where each key is unique and associated with a value. Dictionaries are created using curly braces {} and separate each key-value pair with a colon :. Here’s an example of a dictionary:

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

In this example, the keys are 'name', 'age', and 'city', and their corresponding values are 'John', 30, and 'New York', respectively.

Understanding How to Iterate Through a Dictionary in Python

Python provides several methods to iterate through a dictionary and access its keys, values, or key-value pairs. Let’s explore each method in detail:

Traversing a Dictionary Directly

The most straightforward method to iterate through a dictionary is by traversing it directly. In this approach, you loop over the dictionary, and on each iteration, you get the keys. You can then use these keys to access the corresponding values. Here’s an example:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
for key in my_dict:
value = my_dict[key]
print(f'Key: {key}, Value: {value}')

Output:

Key: name, Value: John
Key: age, Value: 30
Key: city, Value: New York

In this example, the for loop extracts the keys 'name', 'age', and 'city' from the dictionary my_dict. With each iteration, you can access the corresponding values using these keys.

Looping Over Dictionary Items: The .items() Method

Python’s .items() method returns a view object that contains the key-value pairs of a dictionary as tuples. To iterate over the items of a dictionary, you can use this method. Here’s an example:

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

Output:

Key: name, Value: John
Key: age, Value: 30
Key: city, Value: New York

In this example, the for loop iterates over the tuples returned by the .items() method. Each tuple contains a key-value pair, which you can directly assign to separate variables within the loop.

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 = {'name': 'John', 'age': 30, 'city': 'New York'}
for key in my_dict.keys():
print(f'Key: {key}')

Output:

Key: name
Key: age
Key: city

In this example, the for loop iterates over the keys returned by the .keys() method.

Walking Through Dictionary Values: The .values() Method

Similar to .keys(), the .values() method returns a view object containing the values of a dictionary. You can use this method to iterate through the values without accessing their corresponding keys. Here’s an example:

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

Output:

Value: John
Value: 30
Value: New York

In this example, the for loop iterates over the values returned by the .values() method.

Changing Dictionary Values During Iteration

When iterating through a dictionary, you can modify the values of the dictionary. However, it is important to note that modifying the size of the dictionary (adding or deleting items) will raise a RuntimeError. To avoid this, you can create a copy of the dictionary using the dict() function before iterating. Here’s an example:

my_dict = {'a': 1, 'b': 2, 'c': 3}
for key in dict(my_dict):
my_dict[key] *= 2
print(my_dict)

Output:

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

In this example, the code multiplies each value in the dictionary by 2. Creating a copy of the dictionary using dict(my_dict) ensures that the size of the original dictionary doesn’t change during iteration.

Safely Removing Items From a Dictionary During Iteration

To safely remove items from a dictionary during iteration, you can use the .items() method along with a list() or tuple() constructor. This approach creates a copy of the items in the dictionary, which you can then iterate through and delete as needed. Here’s an example:

my_dict = {'a': 1, 'b': 2, 'c': 3}
for key, value in list(my_dict.items()):
if value % 2 == 0:
del my_dict[key]
print(my_dict)

Output:

{'a': 1}

In this example, the code removes all key-value pairs whose values are even. By creating a copy of the items in the dictionary using list(my_dict.items()), you safely iterate and modify the dictionary.

Iterating Through Dictionaries: for Loop Examples

Now let’s explore some practical examples of iterating through dictionaries using for loops.

Filtering Items by Their Value

Suppose you have a dictionary where the values represent the score of each student, and you want to filter out the students who scored below a certain threshold. Here’s an example:

scores = {'John': 80, 'Alice': 75, 'Bob': 90, 'Jane': 85, 'Mark': 70}
passing_score = 80
passing_students = {}
for student, score in scores.items():
if score >= passing_score:
passing_students[student] = score
print(passing_students)

Output:

{'John': 80, 'Bob': 90, 'Jane': 85}

In this example, the code iterates through the items of the scores dictionary and filters out the students whose scores are below the passing threshold. The passing students and their respective scores are added to the passing_students dictionary.

Running Calculations With Keys and Values

Let’s say you have a dictionary with the prices of different items, and you want to calculate the total cost of purchasing multiple items. Here’s an example:

prices = {'apple': 0.5, 'banana': 0.4, 'orange': 0.6, 'grape': 0.3}
shopping_list = {'apple': 3, 'banana': 2, 'orange': 4}
total_cost = 0
for item, quantity in shopping_list.items():
if item in prices:
total_cost += prices[item] * quantity
print(f'Total cost: ${total_cost:.2f}')

Output:

Total cost: $3.70

In this example, the code iterates through the items in the shopping_list dictionary and calculates the total cost by multiplying the price of each item by its quantity. The total cost is accumulated in the total_cost variable.

Swapping Keys and Values Through Iteration

If you have a dictionary where the keys represent categories and the values represent items, you can swap the keys and values using dictionary iteration. Here’s an example:

categories = {'fruit': 'apple', 'vehicle': 'car', 'animal': 'dog'}
items_by_category = {}
for category, item in categories.items():
if item not in items_by_category:
items_by_category[item] = category
print(items_by_category)

Output:

{'apple': 'fruit', 'car': 'vehicle', 'dog': 'animal'}

In this example, the code iterates through the items of the categories dictionary, and for each key-value pair, it swaps the key and value to create a new dictionary items_by_category.

Iterating Through Dictionaries: Comprehension Examples

Python comprehensions provide a concise way to create new dictionaries based on existing dictionaries. They are more readable and often result in more efficient code. Let’s explore two examples of dictionary comprehension.

Filtering Items by Their Value: Revisited

To filter items by their value using dictionary comprehension, you can specify a condition that determines which items should be included in the new dictionary. Here’s an example:

scores = {'John': 80, 'Alice': 75, 'Bob': 90, 'Jane': 85, 'Mark': 70}
passing_score = 80
passing_students = {student: score for student, score in scores.items() if score >= passing_score}
print(passing_students)

Output:

{'John': 80, 'Bob': 90, 'Jane': 85}

In this example, the dictionary comprehension iterates through the items of the scores dictionary and includes only those items whose scores are greater than or equal to the passing score.

Swapping Keys and Values Through Iteration: Revisited

To swap the keys and values of a dictionary using dictionary comprehension, you can create a new dictionary where the values become the keys and vice versa. Here’s an example:

categories = {'fruit': 'apple', 'vehicle': 'car', 'animal': 'dog'}
items_by_category = {item: category for category, item in categories.items()}
print(items_by_category)

Output:

{'apple': 'fruit', 'car': 'vehicle', 'dog': 'animal'}

In this example, the dictionary comprehension iterates through the items of the categories dictionary and creates a new dictionary items_by_category where the values become the keys and the keys become the values.

Traversing a Dictionary in Sorted and Reverse Order

By default, dictionaries in Python are unordered, meaning the order of the keys is arbitrary. However, you can traverse a dictionary in a sorted or reverse-sorted order using the sorted() function or by manipulating the resulting list of keys. Let’s explore some examples.

Iterating Over Sorted Keys

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

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

Output:

a
b
c

In this example, the sorted() function sorts the keys of the dictionary my_dict in ascending order, and the for loop iterates through them.

Looping Through Sorted Values

Similarly, you can iterate through the values of a dictionary in a sorted order using the sorted() function along 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

In this example, the sorted() function sorts the values of the dictionary my_dict in ascending order, and the for loop iterates through them.

Sorting a Dictionary With a Comprehension

If you want to sort a dictionary based on its keys or values and store the sorted items in a new dictionary, you can use a dictionary comprehension along 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.keys())}
print(sorted_dict)

Output:

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

In this example, the dictionary comprehension iterates through the sorted keys of my_dict and creates a new dictionary sorted_dict with the same items but in sorted order 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 along with the sorted() function or directly reverse the resulting list of keys. Here’s an example:

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

Output:

c
b
a

In this example, the reversed() function reverses the order of the keys returned by the sorted() function, and the for loop iterates through them.

Traversing a Dictionary in Reverse Order

Python’s reversed() function can also be used to reverse the order of iteration directly on the dictionary itself. Here’s an example:

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

Output:

c
b
a

In this example, the reversed() function reverses the order of iteration of the dictionary my_dict, and the for loop iterates through the keys in reverse order.

Iterating Over a Dictionary Destructively With .popitem()

Python dictionaries provide the .popitem() method, which removes and returns an arbitrary key-value pair from the dictionary. You can use this method to iteratively pop items from the dictionary until it becomes empty. Here’s an example:

my_dict = {'a': 1, 'b': 2, 'c': 3}
while my_dict:
key, value = my_dict.popitem()
print(f'Key: {key}, Value: {value}')
print(f'Empty Dictionary: {my_dict}')

Output:

Key: c, Value: 3
Key: b, Value: 2
Key: a, Value: 1
Empty Dictionary: {}

In this example, the code uses a while loop to iteratively pop items from the my_dict dictionary until it becomes empty. Each popped item is stored in key and value variables, which can be used within the loop.

Using Built-in Functions to Implicitly Iterate Through Dictionaries

Python provides built-in functions like map() and filter() that can implicitly iterate through dictionaries by applying a transformation or filtering operation to their items.

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

The map() function allows you to apply a specified function to each item of an iterable and return a new iterable with the results. When applied to dictionaries, map() implicitly iterates over the items. Here’s an example:

my_dict = {'a': 1, 'b': 2, 'c': 3}
squared_values = map(lambda item: item[1] ** 2, my_dict.items())
print(list(squared_values))

Output:

[1, 4, 9]

In this example, the map() function applies the lambda function item[1] ** 2 to each item of the my_dict.items() iterable. The resulting squared values are returned as a new iterable, which is then converted to a list.

Filtering Items in a Dictionary: filter()

The filter() function allows you to apply a specified function to each item of an iterable and return a new iterable with the items that satisfy the condition. When applied to dictionaries, filter() implicitly iterates over the items. Here’s an example:

my_dict = {'a': 1, 'b': 2, 'c': 3}
even_values = filter(lambda item: item[1] % 2 == 0, my_dict.items())
print(dict(even_values))

Output:

{'b': 2}

In this example, the filter() function applies the lambda function item[1] % 2 == 0 to each item of the my_dict.items() iterable. The resulting iterable contains only the items where the value is an even number. The filtered items are converted back into a dictionary using the dict() constructor.

Traversing Multiple Dictionaries as One

Python provides two methods to iterate through multiple dictionaries as if they were one: ChainMap and chain().

Iterating Through Multiple Dictionaries With ChainMap

The ChainMap class from the collections module allows you to combine multiple dictionaries into a single view. When iterating through a ChainMap, you can access the keys, values, or items of all combined dictionaries. Here’s an example:

from collections import ChainMap
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
combined_dicts = ChainMap(dict1, dict2)
for key in combined_dicts:
print(key)

Output:

a
b
c
d

In this example, the ChainMap combines the dict1 and dict2 dictionaries into a single view combined_dicts. The for loop iterates through the keys of the combined dictionaries.

Iterating Through a Chain of Dictionaries With chain()

The chain() function from the itertools module allows you to combine multiple iterables into a single iterable. When used with dictionaries, it creates a chain of dictionaries, and you can iterate through their keys, values, or items. Here’s an example:

from itertools import chain
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
combined_dicts = chain(dict1, dict2)
for key in combined_dicts:
print(key)

Output:

a
b
c
d

In this example, the chain() function creates an iterable combined_dicts by chaining the dict1 and dict2 dictionaries together. The for loop iterates through the keys of the combined dictionaries.

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

In Python 3.9 and later versions, you can use the unpacking operator (**) to merge dictionaries during iteration. This allows you to loop over the keys, values, or items of a merged dictionary directly. 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(f'Key: {key}, Value: {value}')

Output:

Key: a, Value: 1
Key: b, Value: 2
Key: c, Value: 3
Key: d, Value: 4

In this example, the code merges the dict1 and dict2 dictionaries using the unpacking operator {**dict1, **dict2}. The for loop then iterates through the items of the merged dictionary.

Key Takeaways

In this tutorial, you learned various techniques to iterate through a dictionary in Python. Specifically, you covered:

  • Traversing a dictionary directly using a for loop
  • Looping over dictionary items using the .items() method
  • Iterating through dictionary keys using the .keys() method
  • Walking through dictionary values using the .values() method
  • Changing dictionary values during iteration
  • Safely removing items from a dictionary during iteration
  • Iterating through dictionaries using for loop examples
  • Iterating through dictionaries using comprehension examples
  • Traversing a dictionary in sorted and reverse order
  • Iterating over a dictionary destructively using .popitem()
  • Using built-in functions to implicitly iterate through dictionaries
  • Traversing multiple dictionaries as one using ChainMap and chain()
  • Looping over merged dictionaries using the unpacking operator (**)

With a solid understanding of dictionary iteration, you can now write more efficient and robust code when working with dictionaries in Python. Happy coding!