How to Loop Through a Dictionary in Python

Python Dictionary

Python dictionaries are a powerful data structure that allow you to store and access data quickly and easily. In this tutorial, we will learn how to loop through a dictionary in Python. We will use the following list of values as an example: ['value1', 'value2', 'value3'].

Using a For Loop

The most common way to loop through a dictionary in Python is by using a for loop. This loop will iterate over each key in the dictionary, and then you can access the corresponding value for that key. Here is an example of how to use a for loop to loop through a dictionary:

my_dict = {'value1': 'foo', 'value2': 'bar', 'value3': 'baz'}
for key in my_dict:
    print(key, my_dict[key])

This code will print out the following:

value1 foo
value2 bar
value3 baz

As you can see, the for loop iterates over each key in the dictionary, and then we can access the corresponding value for that key using the dictionary's get() method.

Using the items() Method

Another way to loop through a dictionary in Python is by using the items() method. This method returns a list of tuples, where each tuple contains a key and its corresponding value. Here is an example of how to use the items() method to loop through a dictionary:

my_dict = {'value1': 'foo', 'value2': 'bar', 'value3': 'baz'}
for key, value in my_dict.items():
    print(key, value)

This code will print out the following:

value1 foo
value2 bar
value3 baz

As you can see, the items() method returns a list of tuples, and then we can use a for loop to iterate over each tuple and access the key and value.

Conclusion

In this tutorial, we learned how to loop through a dictionary in Python. We saw two different ways to do this: using a for loop and using the items() method. Both of these methods are easy to use and can be used to quickly access the data stored in a dictionary.