Advanced Dictionary Handling
Dictionary Comprehensions
Basic Comprehension
## Create dictionary using comprehension
squares = {x: x**2 for x in range(6)}
print(squares)
## Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Conditional Comprehension
## Filtered dictionary comprehension
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
print(even_squares)
## Output: {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
Nested Dictionaries
Creating Nested Dictionaries
## Nested dictionary structure
students = {
'Alice': {
'age': 22,
'grades': {'math': 95, 'science': 90}
},
'Bob': {
'age': 21,
'grades': {'math': 88, 'science': 92}
}
}
Accessing Nested Values
## Accessing nested dictionary values
alice_math_grade = students['Alice']['grades']['math']
print(alice_math_grade) ## Output: 95
Dictionary Merging Techniques
Using update() Method
## Merging dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
dict1.update(dict2)
print(dict1)
## Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Using Unpacking Operator
## Merging with unpacking
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
merged_dict = {**dict1, **dict2}
print(merged_dict)
## Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Dictionary Methods Comparison
Method |
Purpose |
Performance |
update() |
Merge dictionaries |
Moderate |
Unpacking |
Create new dictionary |
Efficient |
dict() Constructor |
Create from pairs |
Flexible |
Advanced Iteration Techniques
## Advanced dictionary iteration
student_scores = {
'Alice': 95,
'Bob': 87,
'Charlie': 92
}
## Iterating with items()
for name, score in student_scores.items():
print(f"{name}: {score}")
## Transforming dictionary values
prices = {'apple': 0.5, 'banana': 0.3, 'orange': 0.6}
discounted_prices = {item: price * 0.9 for item, price in prices.items()}
print(discounted_prices)
Dictionary Operation Workflow
graph TD
A[Dictionary Operations] --> B[Comprehensions]
A --> C[Nested Dictionaries]
A --> D[Merging]
A --> E[Advanced Iteration]
A --> F[Transformation]
Error Handling
## Safe dictionary access
def get_nested_value(dictionary, *keys):
try:
for key in keys:
dictionary = dictionary[key]
return dictionary
except (KeyError, TypeError):
return None
## Example usage
complex_dict = {'a': {'b': {'c': 42}}}
result = get_nested_value(complex_dict, 'a', 'b', 'c')
print(result) ## Output: 42
Best Practices
- Use comprehensions for concise dictionary creation
- Handle nested dictionaries carefully
- Prefer safe access methods
- Consider performance for large dictionaries
Explore these advanced techniques with LabEx to become a Python dictionary expert.