Web Analytics

Dictionary Comprehensions

Intermediate ~20 min read

Dictionary comprehensions are the dictionary equivalent of list comprehensions - they let you create and transform dictionaries in a single, elegant line of code. Once you master them, you'll find yourself using them everywhere to write cleaner, more Pythonic code!

Basic Dictionary Comprehension

The syntax is {key_expr: value_expr for item in iterable}. It's like a loop that builds a dictionary one key-value pair at a time.

Output
Click Run to execute your code
List vs Dict Comprehension: List comprehensions use [] and produce a list. Dict comprehensions use {} with key: value and produce a dictionary. Set comprehensions also use {} but without the colon.

Filtering with Conditions

Add an if clause to filter which items are included in the resulting dictionary. The condition goes at the end of the comprehension.

Output
Click Run to execute your code
Pro Tip: Dict comprehensions are perfect for filtering dictionaries. Instead of looping and conditionally adding items, use {k: v for k, v in dict.items() if condition} for clean, readable filtering.

Transforming Keys and Values

Dict comprehensions shine when you need to transform an existing dictionary - modify keys, values, or both. You can even use if-else expressions for conditional transformations.

Output
Click Run to execute your code
Duplicate Keys Warning: If your key expression produces duplicate keys, later values will overwrite earlier ones silently! For example, {x % 2: x for x in range(5)} results in {0: 4, 1: 3} because keys 0 and 1 get overwritten multiple times.

Practical Use Cases

Dictionary comprehensions are incredibly useful for real-world tasks like creating lookup tables, parsing config strings, inverting dictionaries, and grouping data.

Output
Click Run to execute your code

Common Mistakes

1. Forgetting the colon between key and value

# Wrong - missing colon creates a set!
result = {x for x in range(5)}  # Set: {0, 1, 2, 3, 4}

# Correct - use key: value
result = {x: x**2 for x in range(5)}  # Dict: {0:0, 1:1, ...}

2. Not handling duplicate keys

# Unexpected - later values overwrite earlier
words = ["apple", "ant", "bear"]
first_letter = {word[0]: word for word in words}
print(first_letter)  # {'a': 'ant', 'b': 'bear'} - apple lost!

# If you need all values, use a list
from collections import defaultdict
d = defaultdict(list)
for word in words:
    d[word[0]].append(word)
print(dict(d))  # {'a': ['apple', 'ant'], 'b': ['bear']}

3. Overcomplicating with too much logic

# Hard to read - too complex
result = {k: (v*2 if v > 5 else v*3 if v > 2 else v)
          for k, v in data.items() if k not in exclude}

# Better - break into steps or use regular loop
result = {}
for k, v in data.items():
    if k not in exclude:
        if v > 5:
            result[k] = v * 2
        elif v > 2:
            result[k] = v * 3
        else:
            result[k] = v

4. Using unhashable expressions as keys

# Wrong - lists can't be dictionary keys
d = {[i]: i for i in range(3)}  # TypeError!

# Correct - use tuples instead
d = {(i,): i for i in range(3)}  # Works!

Exercise: Word Lengths

Task: Create a dictionary mapping words to their lengths.

Requirements:

  • Use dictionary comprehension
  • Key = word, Value = length of word
Output
Click Run to execute your code
Show Solution
words = ["apple", "banana", "cherry", "date"]

# Dict comprehension: word -> length
word_lengths = {word: len(word) for word in words}
print(f"Word lengths: {word_lengths}")
# Output: {'apple': 5, 'banana': 6, 'cherry': 6, 'date': 4}

Summary

  • Basic: {key: value for item in iterable}
  • Filter: {k: v for k, v in dict.items() if condition}
  • Transform: {k.upper(): v*2 for k, v in dict.items()}
  • From lists: {k: v for k, v in zip(keys, values)}
  • Conditional value: {k: (v if cond else x) for k, v in items}
  • Watch for: Duplicate keys (later overwrites earlier)
  • Readability: If too complex, use a regular loop

What's Next?

Now let's learn about Nested Data Structures - how to work with lists of dictionaries, dictionaries of lists, and other complex combinations that you'll encounter constantly in real-world Python programming!