Thanks to visit codestin.com
Credit goes to www.pythonmorsels.com

Looping over dictionaries PREMIUM

Trey Hunner smiling in a t-shirt against a yellow wall
Trey Hunner
3 min. read 2 min. video Python 3.10—3.14
Python Morsels
Watch as video
02:13

What happens when you loop over a dictionary in Python?

Take a guess

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.

What actually happens?

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.

Dictionaries see the world through their 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.

Looping with both keys and values

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])

Do you really need a dictionary?

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

It's all about the keys

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?

Now it's your turn! 🚀

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.

Python Morsels
Watch as video
02:13
This is a free preview of a premium screencast. You have 2 previews remaining.