Skip to content

Effortlessly Iterating a Python Dictionary

[

How to Iterate Through a Dictionary in Python

Dictionaries are a fundamental part of the Python programming language and are widely used to store and retrieve data efficiently. To work effectively with dictionaries, it’s important to understand how to iterate through them. In this tutorial, we will explore different methods and techniques for iterating through dictionaries in Python.

Getting Started With Python Dictionaries

Before we dive into dictionary iteration, let’s first understand some basics about dictionaries in Python:

  • Dictionaries are unordered collections of key-value pairs.
  • Keys in a dictionary are unique and immutable, while values can be of any type.
  • Dictionaries are enclosed in curly braces {} and each key-value pair is separated by a colon (:).

Here’s an example of a dictionary:

my_dict = {"apple": 3, "banana": 5, "orange": 2}

In this dictionary, the keys are “apple”, “banana”, and “orange”, and their corresponding values are 3, 5, and 2, respectively.

Understanding How to Iterate Through a Dictionary in Python

Traversing a Dictionary Directly

One way to iterate through a dictionary in Python is to use a for loop to traverse the dictionary directly. This method iterates over the keys of the dictionary. We can then access the values associated with each key.

my_dict = {"apple": 3, "banana": 5, "orange": 2}
for key in my_dict:
print(key, my_dict[key])

Output:

apple 3
banana 5
orange 2

Looping Over Dictionary Items: The .items() Method

Another way to iterate through a dictionary is to use the .items() method. This method returns a view object that contains the key-value pairs of the dictionary. We can then use a for loop to iterate over this view object.

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

Output:

apple 3
banana 5
orange 2

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. We can then iterate over this view object using a for loop.

my_dict = {"apple": 3, "banana": 5, "orange": 2}
for key in my_dict.keys():
print(key)

Output:

apple
banana
orange

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. We can then iterate over this view object using a for loop.

my_dict = {"apple": 3, "banana": 5, "orange": 2}
for value in my_dict.values():
print(value)

Output:

3
5
2

Changing Dictionary Values During Iteration

Sometimes, you may need to update or modify dictionary values while iterating through them. However, you should be cautious when doing so, as it can lead to unexpected results.

One way to safely modify dictionary values during iteration is to create a new dictionary and update its values based on the original dictionary.

my_dict = {"apple": 3, "banana": 5, "orange": 2}
new_dict = {}
for key, value in my_dict.items():
new_dict[key] = value * 2
print(new_dict)

Output:

{'apple': 6, 'banana': 10, 'orange': 4}

In this example, we create a new dictionary new_dict and update its values by multiplying them by 2.

Safely Removing Items From a Dictionary During Iteration

Similarly, if you need to remove items from a dictionary while iterating through it, you should be careful to avoid RuntimeError or skipping elements unintentionally.

One way to safely remove items from a dictionary during iteration is to create a list of keys to be removed, and then remove them outside the loop.

my_dict = {"apple": 3, "banana": 5, "orange": 2}
keys_to_remove = []
for key, value in my_dict.items():
if value > 3:
keys_to_remove.append(key)
for key in keys_to_remove:
del my_dict[key]
print(my_dict)

Output:

{'orange': 2}

In this example, we iterate through the dictionary and add the keys that have a value greater than 3 to the keys_to_remove list. After the loop, we iterate through the keys_to_remove list and remove the corresponding keys from the dictionary.

Iterating Through Dictionaries: for Loop Examples

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

Filtering Items by Their Value

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

Output:

banana 5

In this example, we only print the key-value pairs where the value is greater than 3.

Running Calculations With Keys and Values

my_dict = {"apple": 3, "banana": 5, "orange": 2}
total = 0
for key, value in my_dict.items():
total += len(key) * value
print(total)

Output:

28

In this example, we calculate the total by multiplying the length of each key with its corresponding value and adding it to the total.

Swapping Keys and Values Through Iteration

my_dict = {"apple": 3, "banana": 5, "orange": 2}
new_dict = {}
for key, value in my_dict.items():
new_dict[value] = key
print(new_dict)

Output:

{3: 'apple', 5: 'banana', 2: 'orange'}

In this example, we swap the keys and values of the dictionary by iterating through it and assigning keys as values and values as keys in a new dictionary new_dict.

Iterating Through Dictionaries: Comprehension Examples

Python comprehensions offer a concise way to create new dictionaries based on existing dictionaries. Let’s explore some examples of using dictionary comprehensions to iterate through dictionaries.

Filtering Items by Their Value: Revisited

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

Output:

{'banana': 5}

In this example, we create a new dictionary filtered_dict only containing key-value pairs where the value is greater than 3.

Swapping Keys and Values Through Iteration: Revisited

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

Output:

{3: 'apple', 5: 'banana', 2: 'orange'}

In this example, we create a new dictionary swapped_dict by iterating through the original dictionary and assigning values as keys and keys as values.

Traversing a Dictionary in Sorted and Reverse Order

Python dictionaries are unordered collections, which means the order of the key-value pairs is not guaranteed. However, sometimes we need to traverse dictionaries in sorted or reverse-sorted order. Let’s explore how to achieve this.

Iterating Over Sorted Keys

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

Output:

apple 3
banana 5
orange 2

In this example, we use the sorted() function to sort the keys of the dictionary before iterating through them.

Looping Through Sorted Values

my_dict = {"apple": 3, "banana": 5, "orange": 2}
for value in sorted(my_dict.values()):
for key in my_dict.keys():
if my_dict[key] == value:
print(key, value)

Output:

orange 2
apple 3
banana 5

In this example, we use the sorted() function to sort the values of the dictionary and then iterate through the keys to find the corresponding key for each value.

Sorting a Dictionary With a Comprehension

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

Output:

{'orange': 2, 'apple': 3, 'banana': 5}

In this example, we use a dictionary comprehension with the sorted() function and a lambda function as the key argument to sort the dictionary in ascending order based on its values.

Iterating Through a Dictionary in Reverse-Sorted Order

my_dict = {"apple": 3, "banana": 5, "orange": 2}
for key in sorted(my_dict.keys(), reverse=True):
print(key, my_dict[key])

Output:

orange 2
banana 5
apple 3

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

Traversing a Dictionary in Reverse Order

my_dict = {"apple": 3, "banana": 5, "orange": 2}
for key in reversed(list(my_dict.keys())):
print(key, my_dict[key])

Output:

orange 2
banana 5
apple 3

In this example, we convert the keys of the dictionary to a list, reverse the order using the reversed() function, and then iterate through them.

Iterating Over a Dictionary Destructively With .popitem()

The .popitem() method can be used to iteratively remove and process items from a dictionary. This method removes and returns an arbitrary key-value pair from the dictionary.

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

Output:

orange 2
banana 5
apple 3

In this example, we use a while loop to iteratively remove items from the dictionary using the .popitem() method until the dictionary is empty.

Using Built-in Functions to Implicitly Iterate Through Dictionaries

Python provides built-in functions such as map() and filter() that facilitate dictionary iteration.

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

my_dict = {"apple": 3, "banana": 5, "orange": 2}
transformed_dict = {key: value * 2 for key, value in map(lambda item: (item[0], item[1] * 2), my_dict.items())}
print(transformed_dict)

Output:

{'apple': 6, 'banana': 10, 'orange': 4}

In this example, we use the map() function with a lambda function to apply a transformation to the items of the dictionary before creating a new dictionary transformed_dict.

Filtering Items in a Dictionary: filter()

my_dict = {"apple": 3, "banana": 5, "orange": 2}
filtered_dict = {key: value for key, value in filter(lambda item: item[1] > 3, my_dict.items())}
print(filtered_dict)

Output:

{'banana': 5}

In this example, we use the filter() function with a lambda function to filter the items of the dictionary based on a condition before creating a new dictionary filtered_dict.

Traversing Multiple Dictionaries as One

Python provides several methods and techniques to traverse multiple dictionaries as if they were one.

Iterating Through Multiple Dictionaries With ChainMap

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

Output:

apple 3
banana 5
orange 2
grape 4

In this example, we use the ChainMap class from the collections module to merge two dictionaries into a single dictionary merged_dict. We can then iterate through this merged dictionary as if it were a single dictionary.

Iterating Through a Chain of Dictionaries With chain()

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

Output:

apple 3
banana 5
orange 2
grape 4

In this example, we use the chain() function from the itertools module to concatenate the items of two dictionaries together before creating a new dictionary merged_dict. We can then iterate through this merged dictionary as if it were a single dictionary.

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

Python 3.9 introduced a new feature called the unpacking operator (**) that allows us to merge multiple dictionaries using python’s dictionary unpacking syntax.

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

Output:

apple 3
banana 5
orange 2
grape 4

In this example, we use the unpacking operator (**) to merge dict1 and dict2 into a single dictionary merged_dict. We can then iterate through this merged dictionary as if it were a single dictionary.

Key Takeaways

Iterating through dictionaries in Python is a common task that allows us to access and manipulate the data stored in them. In this tutorial, we explored various methods and techniques for iterating through dictionaries, including direct traversal, using the .items(), .keys(), and .values() methods, changing dictionary values during iteration, safely removing items during iteration, using for loop examples, dictionary comprehensions, and built-in functions, as well as traversing multiple dictionaries as one. Understanding these techniques will help you write more efficient and effective code when working with dictionaries in Python.

We hope this tutorial has provided you with valuable insights into how to iterate through dictionaries in Python.