Skip to content

How to Effortlessly Iterate Over 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 are a fundamental part of the language itself and are used to solve many programming problems that require iterating through a dictionary. In this tutorial, we will dive deep into how to iterate through a dictionary in Python.

Getting Started With Python Dictionaries

Before we dive into iterating through dictionaries, let’s start with a brief overview of Python dictionaries. Dictionaries in Python are unordered collections of key-value pairs. They are defined using curly braces {} and each key-value pair is separated by a colon :. Here is an example:

my_dict = {'name': 'John', 'age': 27, 'gender': 'male'}

In the above example, my_dict is a dictionary with three key-value pairs: 'name': 'John', 'age': 27, and 'gender': 'male'. Each key in a dictionary must be unique.

Understanding How to Iterate Through a Dictionary in Python

There are multiple ways to iterate through a dictionary in Python. In this tutorial, we will explore various methods and provide step-by-step sample codes for each method.

Traversing a Dictionary Directly

The simplest way to iterate through a dictionary is by directly traversing it using a for loop. This way, you iterate over the keys of the dictionary and access the corresponding values. Here is an example:

my_dict = {'name': 'John', 'age': 27, 'gender': 'male'}
for key in my_dict:
value = my_dict[key]
print(key, "->", value)

In the above code, we use a for loop to iterate over my_dict. We access the value of each key using my_dict[key] and print the key-value pairs.

Looping Over Dictionary Items: The .items() Method

Another way to iterate through a dictionary is by using the .items() method. This method returns a view object that contains the key-value pairs of the dictionary. Here is an example:

my_dict = {'name': 'John', 'age': 27, 'gender': 'male'}
for key, value in my_dict.items():
print(key, "->", value)

In this code, we use the .items() method to obtain a view object that contains the key-value pairs of my_dict. We then iterate over this view object and print the key-value pairs.

Iterating Through Dictionary Keys: The .keys() Method

If you only need to iterate 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 is an example:

my_dict = {'name': 'John', 'age': 27, 'gender': 'male'}
for key in my_dict.keys():
value = my_dict[key]
print(key, "->", value)

In this code, we use the .keys() method to obtain a view object that contains the keys of my_dict. We then iterate over this view object and access the values using my_dict[key]. We print the key-value pairs.

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 is an example:

my_dict = {'name': 'John', 'age': 27, 'gender': 'male'}
for value in my_dict.values():
print(value)

In this code, we use the .values() method to obtain a view object that contains the values of my_dict. We then iterate over this view object and print the values.

Changing Dictionary Values During Iteration

It is also possible to change dictionary values during iteration. However, you need to be cautious when modifying dictionary values, as it can lead to unexpected results. Here is an example:

my_dict = {'name': 'John', 'age': 27, 'gender': 'male'}
for key in my_dict:
if key == 'name':
my_dict[key] = 'Alice'
print(my_dict)

In the above code, we check if the key is 'name' during iteration and change its corresponding value to 'Alice'. After the iteration, the dictionary is modified.

Safely Removing Items From a Dictionary During Iteration

If you need to remove items from a dictionary during iteration, it is recommended to create a copy of the dictionary or use the .copy() method. This avoids modifying the dictionary size during iteration, which can lead to unexpected results. Here is an example:

my_dict = {'name': 'John', 'age': 27, 'gender': 'male'}
for key in my_dict.copy():
if key == 'age':
del my_dict[key]
print(my_dict)

In this code, we create a copy of the dictionary using the .copy() method. We then iterate over the copy and delete the key-value pair where the key is 'age'. After the iteration, the dictionary is modified.

Iterating Through Dictionaries: for Loop Examples

Now that we have covered the basics of iterating through dictionaries, let’s explore some more advanced examples using for loops.

Filtering Items by Their Value

Sometimes, you may need to filter items in a dictionary based on their value. Here is an example:

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

In this code, we use a dictionary comprehension to filter items in my_dict where the value is greater than 3. The filtered items are stored in filtered_dict and then printed.

Running Calculations With Keys and Values

You can also perform calculations with the keys and values of a dictionary during iteration. Here is an example:

my_dict = {'apple': 5, 'banana': 3, 'orange': 4, 'grape': 1}
total = sum(value for value in my_dict.values())
average = total https://codemdd.io/ len(my_dict)
print("Total:", total)
print("Average:", average)

In this code, we use a generator expression to calculate the sum of the values in my_dict. We then calculate the average by dividing the total by the length of my_dict. The total and average are then printed.

Swapping Keys and Values Through Iteration

It is also possible to swap the keys and values of a dictionary during iteration. Here is an example:

my_dict = {'apple': 5, 'banana': 3, 'orange': 4, 'grape': 1}
swapped_dict = {value: key for key, value in my_dict.items()}
print(swapped_dict)

In this code, we use a dictionary comprehension to swap the keys and values of my_dict. The swapped key-value pairs are stored in swapped_dict and then printed.

Key Takeaways

In this tutorial, we explored various methods to iterate through a dictionary in Python. We covered traversing a dictionary directly, using the .items(), .keys(), and .values() methods, changing dictionary values during iteration, safely removing items from a dictionary during iteration, and provided examples of advanced techniques using for loops. Solid knowledge of dictionary iteration will help you write better and more robust code.