Categories
Python Answers

How to iterate over dictionaries using for loops with Python?

Spread the love

Sometimes, we want to iterate over dictionaries using for loops with Python.

In this article, we’ll look at how to iterate over dictionaries using for loops with Python.

How to iterate over dictionaries using for loops with Python?

To iterate over dictionaries using for loops with Python, we can use the items method.

For instance, we write:

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

to call the d.items to return an iterable with key and value of each entry of the d dictionary.

In the loop body, we print both with print.

Therefore, we get:

a 1
b 2
c 3

as a result.

Conclusion

To iterate over dictionaries using for loops with Python, we can use the items method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *