Python - Iterate over Dictionary
Python - Iterate over dictionary
To iterate over a dictionary in Python, you can use a For loop. During each iteration you get access to the key of an item in Dictionary. Using the key, you can access the value.
for key in my_dict:
value = my_dict[key]
print(key, value)
If you would like to iterate over only both the key and value of dictionary in For loop, then you may use dict.items() for iterator object in the loop.
for key, value in my_dict.items():
print(key, value)
Video Tutorial
Examples
1. Iterating over dictionary using For loop in Python
We are given a Python dictionary in my_dict. We have to iterate over this dictionary using a Python For loop.
my_dict has three items. We shall iterate over this dictionary using a For loop and the dictionary object as iterator. During each iteration we have access to the key. Using the key, we get the value using dict[key] notation. Having access to both key and value, you may use them based on your requirements, but in this example, we shall just print them.
Python Program
my_dict = {
'apple': 10,
'banana': 20,
'cherry':30
}
for key in my_dict:
value = my_dict[key]
print(key, value)
Output
apple 10
banana 20
cherry 30
2. Iterating over dictionary with access to both key and value from dictionary items() in Python
We are given a Python dictionary in my_dict. We have to iterate over this dictionary using a For loop and the iterator returned by the dictionary items() method.
Python Program
my_dict = {
'apple': 10,
'banana': 20,
'cherry':30
}
for key, value in my_dict.items():
print(key, value)
Output
apple 10
banana 20
cherry 30
Summary
In this tutorial of Python Examples, we learned how to iterate over the dictionary, with the help of well detailed examples.