Practical Techniques
Merging Dictionaries
Using Update Method
def merge_user_profiles(base_profile, new_data):
base_profile.update(new_data)
return base_profile
profile = {"name": "John", "age": 30}
updates = {"city": "New York", "job": "Developer"}
merged_profile = merge_user_profiles(profile, updates)
Unpacking Operator Technique
## Python 3.5+ method
def combine_dictionaries(dict1, dict2):
return {**dict1, **dict2}
result = combine_dictionaries(profile, updates)
Default Dictionary Handling
Using .get() Method
def safe_access(data, key, default_value=None):
return data.get(key, default_value)
user_data = {"username": "alice"}
email = safe_access(user_data, "email", "No email provided")
Collections DefaultDict
from collections import defaultdict
def group_by_category(items):
categories = defaultdict(list)
for item in items:
categories[item['category']].append(item)
return categories
def normalize_keys(data):
return {k.lower(): v for k, v in data.items()}
raw_data = {"Name": "John", "AGE": 30}
normalized = normalize_keys(raw_data)
Value Filtering
def filter_dictionary(data, condition):
return {k: v for k, v in data.items() if condition(v)}
numbers = {"a": 1, "b": 2, "c": 3, "d": 4}
even_numbers = filter_dictionary(numbers, lambda x: x % 2 == 0)
Advanced Techniques
Nested Dictionary Operations
def deep_update(base, update):
for key, value in update.items():
if isinstance(value, dict):
base[key] = deep_update(base.get(key, {}), value)
else:
base[key] = value
return base
flowchart TD
A[Dictionary Operations] --> B{Complexity}
B -->|Lookup| C[O(1) Constant Time]
B -->|Iteration| D[O(n) Linear Time]
B -->|Deep Copy| E[O(n) Linear Time]
Technique Comparison
Technique |
Use Case |
Performance |
Readability |
.update() |
Simple Merging |
Fast |
Good |
Unpacking |
Immutable Merging |
Very Fast |
Excellent |
.get() |
Safe Access |
Constant Time |
Very Good |
Comprehension |
Transformation |
Moderate |
Good |
Error Handling
def robust_dictionary_access(data, *keys):
try:
result = data
for key in keys:
result = result[key]
return result
except (KeyError, TypeError):
return None
nested_data = {"user": {"profile": {"age": 30}}}
age = robust_dictionary_access(nested_data, "user", "profile", "age")
LabEx Best Practices
- Prefer .get() for safe access
- Use comprehensions for clean transformations
- Leverage defaultdict for complex grouping
- Implement robust error handling
By mastering these practical techniques, you'll write more efficient and resilient Python code with LabEx's recommended approaches.