Sign in to your Python Morsels account to save your screencast settings.
Don't have an account yet? Sign up here.
What happens when you loop over a dictionary in Python?
Dictionaries are iterables, which means we can loop over them.
What do you think might happen when we loop over a dictionary?
>>> counts = {"computers": 2, "cats": 1, "ducks": 3, "sandwiches": 0}
>>> for something in counts:
... print(something)
Pause for a moment to think about it.
You might have guessed that when we loop over a dictionary, we would get key-value pairs. But we don't!
>>> for something in counts:
... print(something)
...
computers
cats
ducks
sandwiches
When we loop over a dictionary, we only get the keys.
When we use the in operator to ask whether a dictionary contains something, we're asking about its keys:
>>> "cats" in counts
True
When we remove an item from a dictionary, we're removing it by its key.
>>> del counts["sandwiches"]
Likewise, when we loop over a dictionary, we're looping over the keys:
>>> for something in counts:
... print(something)
...
computers
cats
ducks
You can think of dictionaries as a collection of keys with values attached to those keys.
If you'd like to get both keys and values as you loop, you can always look up the value as you loop by using square brackets ([...]):
>>> for name in counts:
... print(f"We have {counts[name]} {name}")
...
We have 2 computers
We have 1 cats
We have 3 ducks
But there's another way to loop over dictionaries and get the keys and the values at the same time.
Dictionaries have an items method that returns an iterable of two-item tuples.
>>> counts.items()
dict_items([('computers', 2), ('cats', 1), ('ducks', 3)])
The first item in each tuple is a key, and the second item is its value.
So we could loop over our key-value pairs by calling the items method, looping over the result, and using tuple unpacking to split these tuples into keys and values:
>>> for name, count in counts.items():
... print(f"We have {count} {name}")
...
We have 2 computers
We have 1 cats
We have 3 ducks
Using the items method is probably the most common way to loop over a dictionary in Python.
For consistency, dictionaries also have a keys method, which returns an iterable of just the keys:
>>> counts.keys()
dict_keys(['computers', 'cats', 'ducks'])
And a values method, which returns an iterable of just the values:
>>> counts.values()
dict_values([2, 1, 3])
Now, while looping over dictionaries can be useful, they're not the most common data structure to loop over. Dictionaries are typically used for key lookups more often than they're used for looping:
>>> counts = {"computers": 2, "cats": 1, "ducks": 3}
>>> counts["ducks"]
3
If you care about looping, but you don't care about key lookups, you probably don't need a dictionary. If looping is all you need, a list of tuples might be a better way to store your data:
>>> counts = [('computers', 2), ('cats', 1), ('ducks', 3)]
>>> for name, n in counts:
... print(n, name)
...
2 computers
1 cats
3 ducks
When you loop over a dictionary, you'll get keys.
If you'd like to get keys and values, you can use the dictionary items method.
But remember to ask yourself, why am I looping here and do I need a dictionary or would a list be a better way to store my data?
We don't learn by reading or watching. We learn by doing. That means writing Python code.
Practice this topic by working on these related Python exercises.
Sign in to your Python Morsels account to track your progress.
Don't have an account yet? Sign up here.
Sign up for my free 5 day email course and learn essential concepts that introductory courses often overlook: iterables, callables, pointers, duck typing, and namespaces. Learn to avoid beginner pitfalls, in less than a week!
Ready to level up? Sign up now to begin your Python journey the right way!