Dictionary Comprehensions
Dictionary comprehensions provide a concise way to create and transform dictionaries in a single line of code.
## Basic dictionary comprehension
numbers = [1, 2, 3, 4, 5]
squared = {x: x**2 for x in numbers}
## Result: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
## Conditional dictionary comprehension
even_squared = {x: x**2 for x in numbers if x % 2 == 0}
## Result: {2: 4, 4: 16}
Mapping Techniques
1. Using map()
Function
## Transforming dictionary values
original = {'a': 1, 'b': 2, 'c': 3}
transformed = dict(map(lambda k: (k, original[k] * 2), original))
## Result: {'a': 2, 'b': 4, 'c': 6}
2. Dictionary Comprehension with Multiple Sources
## Merging dictionaries
keys = ['name', 'age', 'city']
values = ['Alice', 25, 'New York']
merged = {k: v for k, v in zip(keys, values)}
## Result: {'name': 'Alice', 'age': 25, 'city': 'New York'}
## Transforming nested dictionaries
students = {
'Alice': {'math': 90, 'science': 85},
'Bob': {'math': 80, 'science': 95}
}
## Convert scores to letter grades
letter_grades = {
name: {subject: 'A' if score >= 90 else 'B' if score >= 80 else 'C'
for subject, score in subjects.items()}
for name, subjects in students.items()
}
Method |
Complexity |
Readability |
Performance |
Dictionary Comprehension |
Low |
High |
Moderate |
map() Function |
Moderate |
Moderate |
Good |
Nested Loops |
High |
Low |
Varies |
graph TD
A[Dictionary Transformation] --> B{Transformation Type}
B --> C[Value Modification]
B --> D[Key Modification]
B --> E[Filtering]
B --> F[Nested Transformation]
## Converting keys to uppercase
original = {'name': 'alice', 'age': 25}
uppercase_keys = {k.upper(): v for k, v in original.items()}
## Result: {'NAME': 'alice', 'AGE': 25}
## Efficient large-scale transformation
import timeit
## Comparing transformation methods
def comprehension_method():
return {x: x**2 for x in range(1000)}
def loop_method():
result = {}
for x in range(1000):
result[x] = x**2
return result
## Measure performance
print(timeit.timeit(comprehension_method, number=1000))
print(timeit.timeit(loop_method, number=1000))
LabEx Insight
LabEx recommends practicing these transformation techniques to develop efficient Python dictionary manipulation skills.
Best Practices
- Use comprehensions for simple transformations
- Prefer readability over complexity
- Consider performance for large datasets
- Validate transformed data