## Changing keys
original = {"name": "John", "age": 30}
transformed = {k.upper(): v for k, v in original.items()}
Dictionary Merging Methods
## Using update() method
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
dict1.update(dict2)
## Unpacking operator
merged = {**dict1, **dict2}
Value Manipulation
## Transforming values
prices = {"apple": 0.5, "banana": 0.3}
discounted = {k: v * 0.9 for k, v in prices.items()}
Dictionary Filtering
## Filtering dictionary
original = {"a": 1, "b": 2, "c": 3}
filtered = {k: v for k, v in original.items() if v > 1}
graph TD
A[Dict Transformations] --> B[Key Changes]
A --> C[Value Modifications]
A --> D[Merging]
A --> E[Filtering]
## Transforming nested dictionaries
users = {
"user1": {"name": "Alice", "age": 30},
"user2": {"name": "Bob", "age": 25}
}
transformed_users = {
k: {inner_k: inner_v.upper() if isinstance(inner_v, str) else inner_v
for inner_k, inner_v in v.items()}
for k, v in users.items()
}
Conversion Methods
Method |
Description |
Example |
keys() |
Get dictionary keys |
list(my_dict.keys()) |
values() |
Get dictionary values |
list(my_dict.values()) |
items() |
Get key-value pairs |
list(my_dict.items()) |
## Efficient dictionary transformation
import collections
## Converting dict to defaultdict
regular_dict = {"a": 1, "b": 2}
default_dict = collections.defaultdict(int, regular_dict)
## Grouping and aggregating
data = [
{"name": "Alice", "category": "A"},
{"name": "Bob", "category": "B"},
{"name": "Charlie", "category": "A"}
]
grouped = {}
for item in data:
category = item['category']
if category not in grouped:
grouped[category] = []
grouped[category].append(item['name'])
Best Practices
- Use comprehensions for clean transformations
- Avoid modifying dictionaries during iteration
- Consider performance for large dictionaries
- Leverage LabEx's Python transformation techniques