Practical Dictionary Tricks
Dictionary Comprehensions
## Creating dictionaries dynamically
squares = {x: x**2 for x in range(6)}
print(squares) ## {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
## Filtering dictionaries
even_squares = {k: v for k, v in squares.items() if k % 2 == 0}
Merging Dictionaries
## Python 3.5+ dictionary merging
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
## Merge with unpacking
merged = {**dict1, **dict2}
## Using update() method
dict1.update(dict2)
Dictionary Tricks Comparison
Trick |
Method |
Python Version |
Merging |
{**dict1, **dict2} |
3.5+ |
Merging |
dict1.update(dict2) |
All |
Comprehension |
{k: v for k, v in ...} |
2.7+ |
Nested Dictionary Operations
## Deep copying nested dictionaries
import copy
original = {
"user": {
"name": "Alice",
"settings": {"theme": "dark"}
}
}
## Deep copy prevents reference issues
deep_copy = copy.deepcopy(original)
graph TD
A[Original Dictionary] --> B[Transformation Method]
B --> C{Comprehension}
B --> D{Merging}
B --> E{Filtering}
C --> F[New Dictionary]
D --> F
E --> F
Default Dictionary Handling
from collections import defaultdict
## Automatic default value creation
word_count = defaultdict(int)
text = "hello world hello python"
for word in text.split():
word_count[word] += 1
print(dict(word_count))
Advanced Sorting Techniques
## Sorting dictionaries by value
users = {
"Alice": 35,
"Bob": 28,
"Charlie": 42
}
## Sort by value
sorted_users = dict(sorted(users.items(), key=lambda x: x[1]))
Conditional Dictionary Creation
## Conditional dictionary population
def create_user_dict(name, age=None, email=None):
return {k: v for k, v in [
("name", name),
("age", age),
("email", email)
] if v is not None}
user = create_user_dict("John", age=30)
- Use
dict.get()
for safe access
- Prefer dictionary comprehensions for complex transformations
- Utilize
defaultdict
for automatic initialization
- Avoid repeated dictionary iterations
LabEx Pro Tips
- Leverage dictionary methods for efficient data manipulation
- Understand the performance implications of different dictionary operations
- Practice dictionary comprehensions for concise code
By mastering these practical dictionary tricks, you'll write more elegant and efficient Python code in your LabEx programming projects.