## Converting keys to uppercase
original_dict = {
'apple': 1,
'banana': 2,
'cherry': 3
}
transformed_dict = {key.upper(): value for key, value in original_dict.items()}
Mapping and Converting Values
Value Manipulation
## Multiplying numeric values
prices = {
'laptop': 1000,
'phone': 500,
'tablet': 300
}
discounted_prices = {
item: price * 0.9 for item, price in prices.items()
}
graph TD
A[Original Dictionary] --> B[items() Method]
B --> C{Transformation Strategy}
C --> D[Key Transformation]
C --> E[Value Modification]
C --> F[Filtering]
Pattern |
Description |
Example |
Key Mapping |
Change dictionary keys |
Uppercase/lowercase |
Value Calculation |
Modify values |
Percentage, scaling |
Conditional Filtering |
Selective transformation |
Remove/keep specific items |
## Advanced dictionary transformation
student_data = {
'Alice': {'math': 85, 'science': 90},
'Bob': {'math': 75, 'science': 80},
'Charlie': {'math': 95, 'science': 88}
}
## Calculate average scores
average_scores = {
name: sum(scores.values()) / len(scores)
for name, scores in student_data.items()
}
- Use dictionary comprehensions for efficient transformations
- Minimize redundant iterations
- Consider memory usage with large dictionaries
LabEx encourages exploring these transformation techniques to enhance Python dictionary manipulation skills.