flowchart TD
A[Dictionary Transformations] --> B[Filtering]
A --> C[Mapping]
A --> D[Merging]
A --> E[Inversion]
1. Filtering Dictionaries
Basic Filtering
## Filter dictionary by condition
original = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
filtered = {k: v for k, v in original.items() if v > 2}
## Result: {'c': 3, 'd': 4}
Filtering with Functions
def is_even(item):
return item[1] % 2 == 0
original = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
even_dict = dict(filter(is_even, original.items()))
## Result: {'b': 2, 'd': 4}
Value Mapping
## Transform dictionary values
prices = {'apple': 0.5, 'banana': 0.3, 'orange': 0.6}
tax_prices = {k: v * 1.1 for k, v in prices.items()}
## Result: Adds 10% tax to each price
## Uppercase keys, square values
original = {'a': 1, 'b': 2, 'c': 3}
transformed = {k.upper(): v**2 for k, v in original.items()}
## Result: {'A': 1, 'B': 4, 'C': 9}
3. Dictionary Merging Techniques
Merge Method |
Python Version |
Description |
update() |
All |
Modifies original dictionary |
` |
` Operator |
3.9+ |
{**dict1, **dict2} |
3.5+ |
Unpacking method |
Merging Examples
## Merge dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
## Method 1: update()
dict1.update(dict2)
## Method 2: Merge Operator (Python 3.9+)
merged = dict1 | dict2
## Method 3: Unpacking
merged = {**dict1, **dict2}
4. Dictionary Inversion
Inverting Key-Value Pairs
## Swap keys and values
original = {'a': 1, 'b': 2, 'c': 3}
inverted = {v: k for k, v in original.items()}
## Result: {1: 'a', 2: 'b', 3: 'c'}
Handling Duplicate Values
## Manage duplicate values during inversion
original = {'a': 1, 'b': 2, 'c': 2}
inverted = {}
for k, v in original.items():
inverted.setdefault(v, []).append(k)
## Result: {1: ['a'], 2: ['b', 'c']}
## Transform nested dictionary
users = {
'user1': {'age': 25, 'city': 'New York'},
'user2': {'age': 30, 'city': 'San Francisco'}
}
young_users = {
k: v for k, v in users.items() if v['age'] < 30
}
- Dictionary comprehensions are generally faster
- Use built-in methods for simple transformations
- Be mindful of memory usage with large dictionaries
Best Practices
- Choose the most readable transformation method
- Handle potential key conflicts
- Use type hints for complex transformations
- Consider performance for large datasets
At LabEx, we recommend mastering these dictionary transformation techniques to write more flexible and efficient Python code.