Dictionaries are one of the most useful and flexible data structures in Python. They allow you to store key-value pairs, making it easy to retrieve specific values based on their corresponding keys. In this tutorial, we will learn how to loop through a dictionary using different methods to access both keys and values.
1. Using for loop with dictionary keys
The most basic way to loop through a dictionary is by using a for loop to iterate over the dictionary’s keys. Here, the dict.keys()
method returns an iterable of the dictionary’s keys which we can loop through:
1 2 3 4 |
my_dict = {'a': 1, 'b': 2, 'c': 3} for key in my_dict.keys(): print(key, my_dict[key]) |
However, looping directly over a dictionary will also give you access to its keys by default:
1 2 |
for key in my_dict: print(key, my_dict[key]) |
Both of these approaches will give you the same output:
a 1 b 2 c 3
2. Using for loop with dictionary items
A more efficient way to loop through a dictionary and access both keys and values simultaneously is by using the dict.items()
method. This returns an iterable of (key, value) tuple pairs, which can be unpacked directly within the loop:
1 2 |
for key, value in my_dict.items(): print(key, value) |
This method has the added benefit of being more readable, and it produces the following output:
a 1 b 2 c 3
3. Using dictionary comprehensions
Dictionary comprehensions provide a concise way to perform operations or create new dictionaries based on an existing one. The general syntax is {key_expression: value_expression for key, value in dictionary.items()}
for creating a new transformed dictionary.
For example, let’s double the value of each of the items in my_dict
:
1 2 |
new_dict = {k: v * 2 for k, v in my_dict.items()} print(new_dict) |
This will create a new dictionary with the doubled values and output:
{'a': 2, 'b': 4, 'c': 6}
Full code examples for looping through a dictionary
Here are the full code examples of the methods discussed above:
Looping through keys:
1 2 3 4 |
my_dict = {'a': 1, 'b': 2, 'c': 3} for key in my_dict: print(key, my_dict[key]) |
Looping through items:
1 2 3 4 |
my_dict = {'a': 1, 'b': 2, 'c': 3} for key, value in my_dict.items(): print(key, value) |
Using dictionary comprehensions:
1 2 3 4 |
my_dict = {'a': 1, 'b': 2, 'c': 3} new_dict = {k: v * 2 for k, v in my_dict.items()} print(new_dict) |
Conclusion
In this tutorial, we learned different ways to loop through a dictionary in Python. We covered basic loops using dict.keys()
or iterating directly over a dictionary, more efficient loops using dict.items()
, and dictionary comprehensions for advanced operations. These methods are important to know when working with dictionaries in Python.