Iterating Over Dictionaries
You may already know how to loop over lists and tuples. Just like lists and tuples, dictionaries are iterable too, so that means you can loop over them, for example with a
00:11 In this lesson, I will show you how to loop over dictionaries.
Let’s use the dictionary of US capitals again. When you loop over a dictionary with a
for loop, you iterate over the dictionary keys, so
for state in capitals:
print(state) will print
"New York", and
"Texas". What if you also want to print the city? Well, you already know how to access a value if you know its key, so you can adjust the
print() call and write
and then the
state in square brackets (
So when you run your code, you also print the capitals. So
New York Albany and
That works, but let me show you another way of accomplishing the same. This other way you will see more often in Python code. And that’s using the
.items() dictionary method.
.items() dictionary method returns a list-like object containing tuples of key-value pairs. That means you can loop over the keys and the values simultaneously.
Instead of having
for state in capitals in line 7, you can now write
for state, city in capitals.items():
print(state and now instead of
[state], you can print the
city. When you save and run it, then the output is exactly the same like before, but this code is considered more Pythonic.
Let me explain what happens under the hood. When you loop over
capitals.items(), each iteration of the loop produces a tuple containing the state name and the corresponding capital city name.
By assigning this tuple to
state, city in your
for loop statement, you ensure that the components are unpacked into the two variables
city. And that’s how you loop over a dictionary.
Become a Member to join the conversation.