Dictionary Best Practices
Safe Dictionary Handling
Avoiding KeyError
## Bad Practice
data = {"name": "John"}
## print(data["age"]) ## Raises KeyError
## Good Practice: Using .get() method
print(data.get("age", "Not Found"))
Using defaultdict
from collections import defaultdict
## Automatic default value creation
word_count = defaultdict(int)
text = ["apple", "banana", "apple"]
for word in text:
word_count[word] += 1
Efficient Dictionary Manipulation
Dictionary Comprehensions
## Concise data transformation
squared = {x: x**2 for x in range(5)}
## {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Merging Dictionaries
## Python 3.9+ method
user_info = {"name": "Alice"} | {"age": 30}
## Alternative for earlier versions
user_info = {**{"name": "Alice"}, **{"age": 30}}
graph TD
A[Dictionary Operations] --> B{Performance Factors}
B --> C[Key Lookup]
B --> D[Memory Usage]
B --> E[Iteration Speed]
Key Selection Strategies
Key Type |
Pros |
Cons |
Immutable |
Hashable, Stable |
Limited Flexibility |
Strings |
Readable |
Potential Naming Conflicts |
Tuples |
Complex Keys |
Less Mutable |
Memory-Efficient Practices
## Avoid Redundant Storage
def optimize_storage(data):
return {
k: v for k, v in data.items()
if v is not None
}
Advanced Dictionary Techniques
Nested Dictionary Handling
def deep_get(dictionary, keys, default=None):
for key in keys:
if isinstance(dictionary, dict):
dictionary = dictionary.get(key, default)
else:
return default
return dictionary
complex_data = {
"user": {
"profile": {
"name": "John"
}
}
}
print(deep_get(complex_data, ["user", "profile", "name"]))
Type Hinting and Validation
from typing import Dict, Any
def process_config(config: Dict[str, Any]) -> Dict[str, str]:
## Validate and process configuration
return {
str(k): str(v)
for k, v in config.items()
if v is not None
}
Common Pitfalls to Avoid
- Modifying dictionary during iteration
- Using mutable objects as keys
- Overlooking performance for large dictionaries
collections
module
typing
for type annotations
copy
for deep copying dictionaries
By applying these best practices in your LabEx Python projects, you'll write more robust and efficient dictionary-based code.