Skip to content

Python: Effortlessly Iterate in Dictionary

CodeMDD.io

How to Iterate Through a Dictionary in Python

Dictionaries are fundamental data structures in Python and are widely used to solve various programming problems. In this tutorial, you will learn how to iterate through a dictionary in Python. This knowledge will help you write more robust and efficient code. Let’s explore the different methods of dictionary iteration.

Getting Started With Python Dictionaries

Before we dive into iterating through a dictionary, let’s start by understanding the basics of Python dictionaries. A dictionary is an unordered collection of key-value pairs, where each key is unique. You can create a dictionary using curly braces and separating key-value pairs with a colon:

my_dict = {
"name": "John",
"age": 25,
"country": "USA"
}

Understanding How to Iterate Through a Dictionary in Python

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

Traversing a Dictionary Directly

The most straightforward way to iterate through a dictionary is to traverse it directly using a for loop. This method iterates over the dictionary’s keys and allows you to access the corresponding values:

my_dict = {
"name": "John",
"age": 25,
"country": "USA"
}
for key in my_dict:
print(key, ":", my_dict[key])

This code snippet prints each key-value pair in the dictionary:

name : John
age : 25
country : USA

Looping Over Dictionary Items: The .items() Method

The .items() method allows you to iterate over both the keys and values of a dictionary simultaneously. This method returns a view object, which you can convert into a list if needed. Here’s an example:

my_dict = {
"name": "John",
"age": 25,
"country": "USA"
}
for key, value in my_dict.items():
print(key, ":", value)

This code snippet will produce the same output as the previous example.

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 of the dictionary’s keys, which you can iterate over or convert into a list. Here’s an example:

my_dict = {
"name": "John",
"age": 25,
"country": "USA"
}
for key in my_dict.keys():
print(key)

This code snippet will print each key in the dictionary:

name
age
country

Walking Through Dictionary Values: The .values() Method

Similarly, if you are only interested in iterating through the values of a dictionary, you can use the .values() method. This method returns a view object of the dictionary’s values. Here’s an example:

my_dict = {
"name": "John",
"age": 25,
"country": "USA"
}
for value in my_dict.values():
print(value)

This code snippet will print each value in the dictionary:

John
25
USA

Changing Dictionary Values During Iteration

It is not recommended to change dictionary values during iteration, as it can lead to unexpected results. If you modify the size of the dictionary while iterating through it, you may encounter a runtime error. To avoid this, you can create a copy of the dictionary before iterating or store the keys that need to be modified and update the values after the iteration is complete.

Safely Removing Items From a Dictionary During Iteration

If you need to remove items from a dictionary while iterating, you can use a temporary list to store the keys that need to be removed. After the iteration, you can delete these keys from the dictionary. Here’s an example:

my_dict = {
"name": "John",
"age": 25,
"country": "USA"
}
keys_to_remove = []
for key, value in my_dict.items():
if value == "John":
keys_to_remove.append(key)
for key in keys_to_remove:
del my_dict[key]
print(my_dict)

This code snippet removes the key-value pair where the value is “John” from the dictionary.

Iterating Through Dictionaries: for Loop Examples

Now that you understand the basic methods of dictionary iteration, let’s explore some practical examples using a for loop.

Filtering Items by Their Value

You can filter dictionary items based on a condition. For example, let’s say we want to find all key-value pairs where the value is greater than 30:

my_dict = {
"A": 25,
"B": 40,
"C": 60,
"D": 15
}
for key, value in my_dict.items():
if value > 30:
print(key, ":", value)

The output will be:

B : 40
C : 60

Running Calculations With Keys and Values

You can also perform calculations using the keys and values of a dictionary. For example, let’s calculate the sum of the values in a dictionary:

my_dict = {
"A": 25,
"B": 40,
"C": 60,
"D": 15
}
sum_values = 0
for value in my_dict.values():
sum_values += value
print("Sum of values:", sum_values)

The output will be:

Sum of values: 140

Swapping Keys and Values Through Iteration

Lastly, you can swap the keys and values of a dictionary through iteration. This can be useful in certain scenarios. Here’s an example:

my_dict = {
"A": 25,
"B": 40,
"C": 60,
"D": 15
}
swapped_dict = {}
for key, value in my_dict.items():
swapped_dict[value] = key
print(swapped_dict)

The output will be:

{25: 'A', 40: 'B', 60: 'C', 15: 'D'}

Conclusion

In this tutorial, you learned various methods to iterate through a dictionary in Python. The ability to efficiently navigate and manipulate dictionary data is essential for writing robust code. Remember to choose the appropriate method based on your specific requirements. Keep practicing and experimenting with different use cases to further enhance your skills in dictionary iteration.