How do you build a Python dictionary using dictionary comprehension? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

How do you build a Python dictionary using dictionary comprehension?

message-square
0

Write {key_expr: value_expr for item in iterable} (optionally appending if condition at the end to filter entries) to construct a new Python dictionary in a single, readable, C-optimized expression without pre-allocating an empty {} or calling .update() in a loop.

Basic Example

words = ["apple", "banana", "cherry", "date"]

# 1. Recommended: Map items to computed keys/values
word_lengths = {w: len(w) for w in words}
print(word_lengths)
# Output: {'apple': 5, 'banana': 6, 'cherry': 6, 'date': 4}

# 2. Filter entries with a trailing `if` clause:
long_words = {w.upper(): len(w) for w in words if len(w) >= 6}
print(long_words)
# Output: {'BANANA': 6, 'CHERRY': 6}

# 3. Transform keys/values or swap keys and values from an existing dictionary:
prices_usd = {"laptop": 1000, "mouse": 25, "keyboard": 75}
prices_discounted = {item: round(price * 0.9, 2) for item, price in prices_usd.items()}
print(prices_discounted)
# Output: {'laptop': 900.0, 'mouse': 22.5, 'keyboard': 67.5}

Key Details & Edge Cases

  • Duplicate keys silently overwrite earlier entries (last write wins):
    • If key_expr produces the same key multiple times during iteration, the later pair replaces the earlier value while keeping the key’s first-seen insertion order (e.g., {len(w): w for w in ["cat", "dog"]} evaluates to {3: "dog"}). If you want to group all values sharing a key rather than overwriting, use collections.defaultdict(list) or dict.setdefault().
  • Conditional filtering (if at the end) vs. conditional value assignment (if/else before for):
    • Place if cond after the for clause to exclude keys from the dictionary: {k: v for k, v in items if v > 0}.
    • Place a ternary val_a if cond else val_b before the for clause when every key stays in the dictionary and only its value varies: {k: ("pass" if score >= 50 else "fail") for k, score in grades.items()}.
  • Combining two parallel sequences (zip with strict=True):
    • Pair two lists into a dictionary via {k: v for k, v in zip(keys, values, strict=True)}—or simply dict(zip(keys, values, strict=True)), which avoids comprehension frame overhead when no transformation or filtering is needed.
  • Keep key/value expressions pure and hashable:
    • key_expr must evaluate to a hashable type (str, int, tuple, etc.); using a list or dict as key_expr raises TypeError: unhashable type: 'list'. Avoid mutating external state inside comprehensions—use an explicit for loop when side effects or complex try/except error handling are required.
  • Watch out for braces vs. sets ({x for x in seq} vs. {k: v for ...}):
    • Omitting the colon : creates a set comprehension (set), not a dictionary, and {} alone always creates an empty dict (never an empty set).

Comparison of Dictionary Construction Approaches in Python

Method Supports Key/Value Transformation & Filtering? Speed & Readability Best Used When
{k_expr: v_expr for x in iterable if cond} (Recommended) Yes (arbitrary expressions + if filters) Fast (compiled BUILD_MAP bytecode) & very readable Building a dictionary by computing, transforming, inverting, or filtering items from any iterable.
dict(zip(keys, values, strict=True)) No (1-to-1 pairing as-is) Fastest (pure C constructor call) Directly pairing two equal-length iterables of keys and values without transforming or filtering.
dict.fromkeys(keys, default_val) No (single shared default value) Fastest Initializing all keys to an immutable default (0, None, False—never a mutable []!).
Standard for loop with d[k] = v Yes (supports try/except, logging, grouping) Slightly slower, highest flexibility Multi-line logic, exception handling, or accumulating lists of values per key (defaultdict(list)).