How to Iterate through a dictionary in Python?

Python dictionaries are used to store key-value pairs of data. Sometimes, we need to loop through these key-value pairs in a dictionary to perform certain operations. Python provides multiple ways to iterate over dictionaries using for loop. In this Python example, we will explore some of these ways.

Some of the topics which will be helpful for understanding the program implementation better are:

1. Using items() method

The items() method returns a view object that contains key-value pairs of the dictionary as a tuple. We can loop over this view object using for loop to access the key-value pairs.

dict = {'a': 1, 'b': 2, 'c': 3}
for key, value in dict.items():
  print(key, value)
Output
a 1
b 2
c 3

2. Using keys() method

The keys() method returns a view object that contains the keys of the dictionary. We can loop over this view object using for loop to access the keys and use them to access the corresponding values.

dict = {'a': 1, 'b': 2, 'c': 3}
for key in dict.keys():
  print(key, dict[key])
Output
a 1
b 2
c 3

3. Using values() method

The values() method returns a view object that contains the values of the dictionary. We can loop over this view object using for loop to access the values.

dict = {'a': 1, 'b': 2, 'c': 3}
for value in dict.values():
  print(value)
Output
1
2
3

4. Using list comprehension method

We can use list comprehension to create a list of key-value pairs and then loop over it using for loop.

dict = {'a': 1, 'b': 2, 'c': 3}
key_value_list = [(key, value) for key, value in dict.items()]
for key, value in key_value_list:
  print(key, value)
Output
a 1
b 2
c 3

5. Conclusion

These programs are elementary examples of how we can use iterate dictionaries. We can perform many other operations like sorting, filtering etc which we will explore in other examples.


Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Also for examples in Python and practice please refer to Python Examples.

Complete code samples are present on Github project.

Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! ?

Recommended -

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Index