Python Basics — Dictionary Comprehensions

2 minute read

Dictionary Comprehensions

Just like list comprehensions, Python supports a concise way to build dictionaries from iterables.

Basic Syntax

{key_expr: value_expr for item in iterable}
# Squares dictionary
squares = {x: x ** 2 for x in range(6)}
print(squares)
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Conditional Filtering

# Only even numbers
even_squares = {x: x ** 2 for x in range(10) if x % 2 == 0}
print(even_squares)
# {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}

Transforming Dictionaries

Swap Keys and Values

original = {"a": 1, "b": 2, "c": 3}
inverted = {v: k for k, v in original.items()}
print(inverted)
# {1: 'a', 2: 'b', 3: 'c'}

Filter by Value

scores = {"Alice": 95, "Bob": 67, "Charlie": 82, "Diana": 45}
passed = {name: score for name, score in scores.items() if score >= 70}
print(passed)
# {'Alice': 95, 'Charlie': 82}

Transform Values

prices_usd = {"apple": 1.20, "banana": 0.50, "cherry": 2.00}
prices_cents = {item: int(price * 100) for item, price in prices_usd.items()}
print(prices_cents)
# {'apple': 120, 'banana': 50, 'cherry': 200}

Transform Keys

data = {"Name": "Alice", "AGE": 30, "City": "NYC"}
normalized = {k.lower(): v for k, v in data.items()}
print(normalized)
# {'name': 'Alice', 'age': 30, 'city': 'NYC'}

Real-World Examples

Word Count

text = "the cat sat on the mat the cat"
words = text.split()
word_count = {word: words.count(word) for word in set(words)}
print(word_count)
# {'cat': 2, 'on': 1, 'the': 3, 'mat': 1, 'sat': 1}

For large texts, collections.Counter is more efficient.

Grouping by Length

words = ["hi", "hello", "hey", "howdy", "go", "good"]
by_length = {}
for word in words:
    by_length.setdefault(len(word), []).append(word)
print(by_length)
# {2: ['hi', 'go'], 5: ['hello', 'howdy'], 3: ['hey'], 4: ['good']}

Character Frequency

text = "hello world"
freq = {ch: text.count(ch) for ch in set(text) if ch != " "}
print(freq)
# {'h': 1, 'e': 1, 'l': 3, 'o': 2, 'w': 1, 'r': 1, 'd': 1}

From Two Lists

keys = ["name", "age", "city"]
values = ["Alice", 30, "New York"]

d = {k: v for k, v in zip(keys, values)}
print(d)
# {'name': 'Alice', 'age': 30, 'city': 'New York'}

dict(zip(keys, values)) is simpler for this specific case.

Nested Dictionary Comprehension

# Multiplication table
table = {
    i: {j: i * j for j in range(1, 6)}
    for i in range(1, 4)
}
print(table)
# {1: {1: 1, 2: 2, 3: 3, 4: 4, 5: 5},
#  2: {1: 2, 2: 4, 3: 6, 4: 8, 5: 10},
#  3: {1: 3, 2: 6, 3: 9, 4: 12, 5: 15}}

When NOT to Use

Avoid comprehensions that are hard to read:

# ❌ Too complex
result = {k: [v for v in vals if v > threshold]
          for k, vals in data.items()
          if any(v > threshold for v in vals)}

# ✅ Better as a loop
result = {}
for k, vals in data.items():
    filtered = [v for v in vals if v > threshold]
    if filtered:
        result[k] = filtered

Summary

  • {key: value for item in iterable} — basic dict comprehension
  • {key: value for item in iterable if condition} — with filter
  • Invert: {v: k for k, v in d.items()}
  • Transform keys/values in one expression
  • Keep comprehensions simple and readable

Next up: Nested Dictionaries →

Updated: