Complex Dictionary Usage
Nested Dictionaries
Creating and Accessing Nested Structures
## Nested dictionary representing a school
school = {
"class_A": {
"students": ["Alice", "Bob", "Charlie"],
"teacher": "Mr. Smith",
"subjects": ["Math", "Science"]
},
"class_B": {
"students": ["David", "Eve", "Frank"],
"teacher": "Ms. Johnson",
"subjects": ["History", "Literature"]
}
}
## Accessing nested elements
print(school["class_A"]["students"][1]) ## Output: Bob
Dictionary with Complex Value Types
Mixed Data Type Values
## Dictionary with mixed value types
complex_dict = {
"user": {
"name": "John Doe",
"age": 30,
"skills": ["Python", "Data Analysis"],
"is_active": True,
"metadata": None
}
}
Advanced Dictionary Techniques
Defaultdict for Automatic Initialization
from collections import defaultdict
## Creating a defaultdict with list as default factory
word_count = defaultdict(list)
## Automatically creates list for new keys
word_count['python'].append('programming')
word_count['python'].append('language')
Filtering and Mapping
## Filtering dictionary
original_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
filtered_dict = {k: v for k, v in original_dict.items() if v > 2}
## Result: {'c': 3, 'd': 4}
## Transforming dictionary values
transformed_dict = {k: v * 2 for k, v in original_dict.items()}
## Result: {'a': 2, 'b': 4, 'c': 6, 'd': 8}
Dictionary Operation Workflow
graph TD
A[Dictionary Complex Operations] --> B{Operation Type}
B --> |Nesting| C[Nested Dictionaries]
B --> |Transformation| D[Filtering/Mapping]
B --> |Dynamic Creation| E[DefaultDict]
B --> |Advanced Manipulation| F[Custom Logic]
Operation |
Time Complexity |
Best Practices |
Nested Access |
O(1) |
Use .get() for safety |
Filtering |
O(n) |
List comprehensions |
Transformation |
O(n) |
Generator expressions |
Advanced Use Cases
Dictionary as Caching Mechanism
def expensive_function(x):
## Simulating an expensive computation
return x * x
## Memoization using dictionary
class Memoize:
def __init__(self, fn):
self.fn = fn
self.cache = {}
def __call__(self, *args):
if args not in self.cache:
self.cache[args] = self.fn(*args)
return self.cache[args]
## Usage
@Memoize
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
Key Takeaways
- Nested dictionaries provide complex data representation
- Use defaultdict for automatic initialization
- Leverage dictionary comprehensions for transformations
- Consider performance implications of complex operations
By mastering these advanced techniques, you'll unlock powerful dictionary manipulation skills with LabEx, enabling more sophisticated Python programming solutions.