Nested Dictionary Conversion
## Transforming nested structures
data = [
{'category': 'fruits', 'name': 'apple', 'price': 1.5},
{'category': 'fruits', 'name': 'banana', 'price': 2.0},
{'category': 'vegetables', 'name': 'carrot', 'price': 1.0}
]
grouped_dict = {}
for item in data:
category = item['category']
if category not in grouped_dict:
grouped_dict[category] = {}
grouped_dict[category][item['name']] = item['price']
## Using functional programming
from functools import reduce
def transform_dict(items, key_func, value_func):
return {key_func(item): value_func(item) for item in items}
## Example usage
students = [
{'name': 'Alice', 'scores': [85, 90, 92]},
{'name': 'Bob', 'scores': [75, 80, 85]}
]
avg_scores = transform_dict(
students,
key_func=lambda x: x['name'],
value_func=lambda x: sum(x['scores']) / len(x['scores'])
)
graph TD
A[Original Data] --> B[Transformation Function]
B --> C[Transformed Dictionary]
C --> D[New Data Structure]
Conversion Techniques Comparison
Technique |
Complexity |
Flexibility |
Use Case |
Dict Comprehension |
O(n) |
High |
Simple transformations |
Functional Mapping |
O(n) |
Very High |
Complex transformations |
Reduce Method |
O(n) |
Moderate |
Aggregation |
Dynamic Key Generation
## Dynamic key generation
def create_dynamic_dict(items, key_strategy, value_strategy):
return {
key_strategy(item): value_strategy(item)
for item in items
}
## Example: Creating a dict with custom keys
data = [
{'id': 1, 'name': 'Alice', 'department': 'HR'},
{'id': 2, 'name': 'Bob', 'department': 'IT'}
]
## Create dict with department as key and names as values
dept_dict = create_dynamic_dict(
data,
key_strategy=lambda x: x['department'],
value_strategy=lambda x: x['name']
)
At LabEx, we emphasize efficient transformation techniques that minimize computational overhead.
Lazy Evaluation with Generators
## Lazy transformation with generators
def lazy_dict_transform(items):
for item in items:
yield (item['key'], item['value'])
## Memory-efficient transformation
transformed = dict(lazy_dict_transform(large_dataset))
def safe_transform(items, transform_func):
try:
return {k: transform_func(v) for k, v in items.items()}
except Exception as e:
print(f"Transformation error: {e}")
return {}
Advanced Merging Techniques
## Merging dictionaries with custom logic
def merge_dicts(dict1, dict2, merge_func=lambda x, y: y):
return {
k: merge_func(dict1.get(k), dict2.get(k))
for k in set(dict1) | set(dict2)
}
Time Complexity Analysis
- Simple transformations: O(n)
- Complex transformations: O(n log n)
- Nested transformations: O(nÂē)
Memory Optimization Strategies
- Use generators for large datasets
- Implement lazy evaluation
- Minimize intermediate data structures