
Iterate over dictionary.items() using tuple unpacking (for key, value in data.items(): print(f"{key}: {value}")) to access both the key and its associated value directly in $O(1)$ per step without extra hash lookups—preserving insertion order automatically in Python 3.7+.
Basic Example
user_scores = {"Alice": 95, "Bob": 82, "Charlie": 91}
# 1. Recommended: Unpack key and value directly via .items()
for name, score in user_scores.items():
print(f"{name}: {score}")
# Output:
# Alice: 95
# Bob: 82
# Charlie: 91
# 2. Loop in sorted key order (without modifying the original dict):
for name, score in sorted(user_scores.items()):
print(f"{name} -> {score}")
# 3. Include a 1-based row index with enumerate():
for idx, (name, score) in enumerate(user_scores.items(), start=1):
print(f"{idx}. {name} = {score}")
Key Details & Edge Cases
- Never mutate (add or delete keys in) a dictionary while iterating over
.items():- Adding or removing keys inside
for k, v in d.items():immediately raisesRuntimeError: dictionary changed size during iteration. If you need to filter or delete keys while looping, iterate over a snapshot copy (for k, v in list(d.items()):) or build a new dict with a dictionary comprehension ({k: v for k, v in d.items() if v >= 90}).
- Adding or removing keys inside
- Do not write
for k in d: print(k, d[k])when you need both keys and values:- Iterating directly over
dyields only keys, forcing a redundant hash table lookupd[k]on every iteration.d.items()yields(key, value)pairs directly from the underlying table entries in a single pass.
- Iterating directly over
- Remember parentheses when combining
enumerate()with.items():enumerate(d.items())yields(index, (key, value))tuples—so you must writefor i, (k, v) in enumerate(d.items()):(omitting the inner parentheses raisesValueError: not enough values to unpack (expected 3, got 2)).
.items()returns a dynamicdict_itemsview, not a static list:- In Python 3,
d.items()is a lightweight view object ($O(1)$ memory) that reflects live updates todand supports set-like intersections (d1.items() & d2.items()when values are hashable). Wrap it inlist(d.items())only if you need indexing (items[0]) or safe iteration while mutatingd.
- In Python 3,
- Pretty-printing nested dictionaries (
pprintorjson.dumps):- For deeply nested dictionaries, looping at the top level prints raw
representations for nested values; usepprint.pprint(d, sort_dicts=False)orjson.dumps(d, indent=2)for clean multi-line output.
- For deeply nested dictionaries, looping at the top level prints raw
Comparison of Dictionary Iteration Patterns in Python
| Pattern | Yields | Extra Lookup d[k] Needed? |
Safe to Add/Delete Keys During Loop? | Best Used When |
|---|---|---|---|---|
for k, v in d.items(): (Recommended) |
(key, value) pairs |
No | No (RuntimeError) |
Standard iteration when you need both keys and values in insertion order. |
for k, v in sorted(d.items()): |
(key, value) sorted by key |
No | Yes (sorted() creates a list copy) |
Printing deterministic, alphabetically or numerically sorted key-value output. |
for k, v in list(d.items()): |
(key, value) from a static snapshot |
No | Yes | Deleting (del d[k]) or inserting keys conditionally while iterating. |
for k in d: / for v in d.values(): |
Keys only / Values only | d[k] if value needed / N/A |
No (RuntimeError) |
Loops that genuinely inspect only keys or only values without needing the other. |
You must log in or register to comment.
