Topic 28 of 58
Dict Comprehensions
Overview
Much like list comprehensions, dictionary comprehensions provide an incredibly succinct and elegant syntax for generating dictionaries from existing iterables. They eliminate the need for boilerplate for loops and empty dictionary declarations. You can map values, swap keys and values, or conditionally filter datasets in a single, highly-optimized line of code.
Syntax
python
names = ["Alice", "Bob", "Charlie"]
# Basic Dict Comprehension
# Syntax: {key_expr: value_expr for item in iterable}
name_lengths = {name: len(name) for name in names}
# {'Alice': 5, 'Bob': 3, 'Charlie': 7}
# Adding conditional filtering
long_names = {name: length for name, length in name_lengths.items() if length > 4}
# {'Alice': 5, 'Charlie': 7}
# Generating a dictionary from a range
squares = {num: num**2 for num in range(1, 4)}
# {1: 1, 2: 4, 3: 9}Common Pitfalls
- Confusing Set Comprehensions with Dict Comprehensions. Both use curly braces
{}. The distinguishing factor is the colon:. If the expression has a colon mapping keys to values ({k:v for...}), it's a dict. If it's single values ({x for...}), it's a set.
Interview Questions
Q:
How can you easily invert a dictionary (swap all its keys and values) using comprehension?
A:
By iterating over the items and reversing the assignment order: inverted = {value: key for key, value in original_dict.items()}. Note: This only works if all original values are unique and hashable.
Real-World Example
Mapping database IDs to user objects for instantly accessible O(1) lookups.
example
python
users = [
{"id": 101, "name": "Alice"},
{"id": 102, "name": "Bob"}
]
# Convert the list to a dictionary mapped by ID
user_index = {user["id"]: user for user in users}
# Now we can find a user instantly by ID
print(user_index[102]["name"]) # BobCheck Your Knowledge
Test your understanding of Dict Comprehensions with these quick questions.