Menu Close

How to iterate over dictionaries using for loops with Python?

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.

Posted in Python, Python Answers