CodeMIRAI
0 XP

Looping over dictionaries

2 min read 7 runnable examples Quiz included

Looping over a dictionary

Looping over a dictionary directly gives you its keys:

Python
ages = {"Asha": 21, "Leo": 30, "Mei": 24}
for name in ages:
    print(name)

Three methods give you different views:

Python
ages = {"Asha": 21, "Leo": 30, "Mei": 24}
print(ages.keys())
print(ages.values())
print(ages.items())

items() gives (key, value) pairs, which you unpack in the loop. This is the most common way to loop:

Python
ages = {"Asha": 21, "Leo": 30, "Mei": 24}
for name, age in ages.items():
    print(f"{name} is {age}")

print("Average age:", sum(ages.values()) / len(ages))

Updating and merging

Python
settings = {"theme": "light", "font": 14}
settings.update({"theme": "dark", "language": "en"})
print(settings)

defaults = {"theme": "light", "font": 14, "autosave": True}
user = {"font": 18}
merged = defaults | user        # Python 3.9+: right side wins
print(merged)

Sorting a dictionary

Dictionaries themselves aren't sorted, but you can loop over them in sorted order:

Python
scores = {"Asha": 92, "Leo": 78, "Mei": 85, "Raj": 95}

for name in sorted(scores):                      # by key
    print(name, scores[name])
print()
for name, score in sorted(scores.items(), key=lambda kv: kv[1], reverse=True):
    print(name, score)                           # by value, highest first

The key=lambda kv: kv[1] part says "sort by the second element of each pair", the value. You will learn about lambda in the Functions module.

setdefault: grouping

setdefault(key, default) returns the value for key, first inserting default if the key is missing. It's ideal for grouping:

Python
words = ["apple", "avocado", "banana", "blueberry", "cherry"]
by_letter = {}
for w in words:
    by_letter.setdefault(w[0], []).append(w)
print(by_letter)

Copying

Like lists, assigning a dictionary to another name doesn't copy it. Use .copy() or dict(original) for an independent copy.

Python
original = {"a": 1}
copy = original.copy()
copy["b"] = 2
print(original, copy)
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.