How to iterate a dict in Python
Use `for k, v in d.items()` for key+value pairs. `for k in d` iterates just the keys (default).
user = {"name": "Alice", "age": 30, "city": "Berlin"}
for key, value in user.items():
print(f"{key}: {value}").items() yields (key, value) tuples, which unpack cleanly into two names in the for-loop. This is the default idiom when you need both.
Bare `for k in d` iterates the keys β the same as `for k in d.keys()` but slightly shorter. Since Python 3.7 the iteration order matches insertion order, so this is deterministic (unlike dicts in Python 3.6 and earlier).
.values() yields just the values β useful when the keys don't matter for the operation.
Variations
Just the keys
for key in user:
print(key)Equivalent to `for key in user.keys()` β shorter is idiomatic.
Just the values
for value in user.values():
print(value)When you don't need the keys at all.
Sorted iteration
for k, v in sorted(user.items()):
print(k, v)sorted() by key alphabetically. Pass key=lambda x: x[1] to sort by value.
Get one Python lesson + one career idea every Friday
No spam, no "buy our course now". Three bullets, every Friday. Unsubscribe with one click.