Iterating over dictionaries using 'for' loops

To iterate over a dictionary using a for loop, you can use the .items() method to get a list of the dictionary's keys and values, and then iterate over that list. Here is an example:

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

This will output:

a 1
b 2
c 3

Watch a course Python - The Practical Guide

You can also use the .keys() method to iterate just over the keys or the .values() method to iterate just over the values. Here is an example using .keys():

for key in d.keys():
    print(key)

This will output:

a
b
c

And here is an example using .values():

for value in d.values():
    print(value)

This will output:

1
2
3