Advanced Techniques
Nested Dict Comprehensions
Multi-Level Dictionary Creation
## Create a nested dictionary with comprehension
matrix = {
x: {y: x * y for y in range(1, 4)}
for x in range(1, 4)
}
print(matrix)
## Output: {1: {1: 1, 2: 2, 3: 3}, 2: {1: 2, 2: 4, 3: 6}, 3: {1: 3, 2: 6, 3: 9}}
Dynamic Key and Value Generation
## Advanced conditional dict comprehension
data = [1, 2, 3, 4, 5]
result = {
x: ('even' if x % 2 == 0 else 'odd', x**2)
for x in data
}
print(result)
## Output: {1: ('odd', 1), 2: ('even', 4), 3: ('odd', 9), 4: ('even', 16), 5: ('odd', 25)}
Lazy Evaluation with Generator Expressions
## Combining dict comprehension with generator expressions
def lazy_dict_creation(limit):
return {
x: x**2
for x in (num for num in range(limit) if num % 2 == 0)
}
print(lazy_dict_creation(10))
## Output: {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
Advanced Filtering Techniques
Complex Condition Filtering
## Multi-condition filtering
students = [
{'name': 'Alice', 'grade': 85, 'age': 22},
{'name': 'Bob', 'grade': 92, 'age': 25},
{'name': 'Charlie', 'grade': 78, 'age': 20}
]
advanced_filter = {
student['name']: student
for student in students
if student['grade'] > 80 and student['age'] > 22
}
print(advanced_filter)
## Output: {'Bob': {'name': 'Bob', 'grade': 92, 'age': 25}}
Dict Comprehension with External Functions
def complex_key_generator(item):
return f"{item['category']}_{item['id']}"
def value_transformer(item):
return item['value'] * 2
data = [
{'id': 1, 'category': 'A', 'value': 10},
{'id': 2, 'category': 'B', 'value': 20}
]
transformed_dict = {
complex_key_generator(item): value_transformer(item)
for item in data
}
print(transformed_dict)
## Output: {'A_1': 20, 'B_2': 40}
Error Handling and Robustness
Safe Dict Comprehension
## Handle potential errors during dict comprehension
def safe_conversion(value):
try:
return int(value)
except ValueError:
return None
raw_data = ['1', '2', 'three', '4', 'five']
safe_dict = {
index: safe_conversion(value)
for index, value in enumerate(raw_data)
}
print(safe_dict)
## Output: {0: 1, 1: 2, 2: None, 3: 4, 4: None}
Workflow Visualization
graph TD
A[Input Data] --> B{Advanced Dict Comprehension}
B --> C[Nested Transformation]
B --> D[Complex Filtering]
B --> E[Function Mapping]
C --> F[Result Dictionary]
D --> F
E --> F
Advanced Techniques Comparison
Technique |
Complexity |
Performance |
Use Case |
Basic Dict Comprehension |
Low |
High |
Simple Transformations |
Nested Comprehension |
Medium |
Medium |
Complex Structures |
Function-Based |
High |
Low |
Dynamic Transformations |
LabEx Pro Tip
Advanced dict comprehensions require careful design. LabEx recommends maintaining a balance between complexity and readability to ensure maintainable code.