How To Loop Through A Dictionary In Python

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:

However, looping directly over a dictionary will also give you access to its keys by default:

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:

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:

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:

Looping through items:

Using dictionary comprehensions:

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.