Dictionary transformation involves modifying, converting, or restructuring dictionaries to meet specific programming requirements. This section explores various techniques for transforming dictionaries efficiently.
## Changing dictionary keys
original_dict = {"name": "Alice", "age": 30}
transformed_dict = {k.upper(): v for k, v in original_dict.items()}
print(transformed_dict) ## Output: {"NAME": "Alice", "AGE": 30}
## Transforming dictionary values
prices = {"apple": 0.5, "banana": 0.3, "orange": 0.6}
discounted_prices = {k: v * 0.9 for k, v in prices.items()}
print(discounted_prices) ## 10% discount on all prices
3. Filtering Dictionaries
## Filtering dictionary based on conditions
data = {"a": 10, "b": 20, "c": 30, "d": 40}
filtered_data = {k: v for k, v in data.items() if v > 20}
print(filtered_data) ## Output: {"c": 30, "d": 40}
## Transforming nested dictionaries
students = {
"Alice": {"math": 90, "science": 85},
"Bob": {"math": 75, "science": 80}
}
## Calculate average scores
avg_scores = {
name: sum(scores.values()) / len(scores)
for name, scores in students.items()
}
print(avg_scores)
Strategy |
Description |
Use Case |
Comprehension |
Quick, inline transformation |
Simple modifications |
map() |
Apply function to dictionary |
Complex transformations |
Custom Functions |
Detailed logic implementation |
Advanced scenarios |
Dictionary Type Conversion
## Converting between dictionary types
original_dict = {"a": 1, "b": 2, "c": 3}
## Convert to list of tuples
tuple_list = list(original_dict.items())
## Convert back to dictionary
converted_dict = dict(tuple_list)
graph TD
A[Source Dictionary] --> B{Transformation Method}
B --> C[Key Transformation]
B --> D[Value Transformation]
B --> E[Filtering]
B --> F[Type Conversion]
- Use dictionary comprehensions for simple transformations
- Leverage built-in methods when possible
- Avoid unnecessary deep copying
- Consider memory usage for large dictionaries
## Combining multiple transformations
def transform_dict(data):
return {
k.upper(): v * 2
for k, v in data.items()
if isinstance(v, (int, float))
}
sample_data = {"x": 10, "y": 20, "z": "hello"}
result = transform_dict(sample_data)
print(result) ## Uppercase keys, numeric values doubled
Best Practices for LabEx Learners
- Choose the most readable transformation method
- Use type hints for complex transformations
- Handle potential exceptions
- Optimize for readability and performance
By mastering these dictionary transformation techniques, you'll enhance your Python data manipulation skills in the LabEx learning environment.