Practical Dict Techniques
Dictionary Comprehensions
Dictionary comprehensions provide a concise way to create dictionaries with compact, readable code.
## Basic dictionary comprehension
squares = {x: x**2 for x in range(6)}
## Result: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
## Conditional dictionary comprehension
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
## Result: {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
Merging Dictionaries
## Python 3.9+ method
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged_dict = dict1 | dict2
## Previous versions method
combined_dict = {**dict1, **dict2}
graph TD
A[Dict Transformation] --> B[Filtering]
A --> C[Mapping]
A --> D[Inverting]
A --> E[Nesting]
Key Techniques
## Dictionary Methods Demonstration
student_grades = {
"Alice": 95,
"Bob": 87,
"Charlie": 92
}
## Key operations
print(student_grades.keys()) ## Dict keys
print(student_grades.values()) ## Dict values
print(student_grades.items()) ## Key-value pairs
Advanced Dict Manipulation
Technique |
Method |
Description |
Filtering |
dict comprehension |
Create new dict with conditions |
Merging |
` |
or update()` |
Sorting |
sorted() |
Sort dictionary by keys/values |
from collections import Counter
## Counting occurrences efficiently
words = ['apple', 'banana', 'apple', 'cherry', 'banana']
word_count = Counter(words)
## Result: Counter({'apple': 2, 'banana': 2, 'cherry': 1})
## Most common elements
print(word_count.most_common(2))
Safe Dictionary Operations
## Using get() with default value
user_data = {}
age = user_data.get('age', 0) ## Returns 0 if 'age' not found
## Setdefault method
user_data.setdefault('name', 'Anonymous')
Nested Dictionary Handling
## Deep dictionary access with nested get()
complex_dict = {
'users': {
'admin': {'permissions': ['read', 'write']}
}
}
## Safe nested access
permissions = complex_dict.get('users', {}).get('admin', {}).get('permissions', [])
Best Practices
- Use comprehensions for readability
- Leverage built-in dictionary methods
- Handle missing keys gracefully
- Consider performance implications
At LabEx, we recommend mastering these practical dictionary techniques to write more efficient Python code.