How do you loop through and print key-value pairs from a Python dictionary? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

How do you loop through and print key-value pairs from a Python dictionary?

message-square
0
1
How do you loop through and print key-value pairs from a Python dictionary?

How do you loop through and print key-value pairs from a Python dictionary? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago
How do you loop through and print key-value pairs from a Python dictionary? | A1Lab

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 raises RuntimeError: 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}).
  • Do not write for k in d: print(k, d[k]) when you need both keys and values:
    • Iterating directly over d yields only keys, forcing a redundant hash table lookup d[k] on every iteration. d.items() yields (key, value) pairs directly from the underlying table entries in a single pass.
  • Remember parentheses when combining enumerate() with .items():
    • enumerate(d.items()) yields (index, (key, value)) tuples—so you must write for i, (k, v) in enumerate(d.items()): (omitting the inner parentheses raises ValueError: not enough values to unpack (expected 3, got 2)).
  • .items() returns a dynamic dict_items view, not a static list:
    • In Python 3, d.items() is a lightweight view object ($O(1)$ memory) that reflects live updates to d and supports set-like intersections (d1.items() & d2.items() when values are hashable). Wrap it in list(d.items()) only if you need indexing (items[0]) or safe iteration while mutating d.
  • Pretty-printing nested dictionaries (pprint or json.dumps):
    • For deeply nested dictionaries, looping at the top level prints raw {...} representations for nested values; use pprint.pprint(d, sort_dicts=False) or json.dumps(d, indent=2) for clean multi-line output.

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.