Practical Mapping Examples
Real-World Dictionary Mapping Scenarios
Dictionaries are powerful tools for solving various programming challenges. This section explores practical applications of dictionary mapping in Python.
1. User Profile Management
def create_user_profile(name, age, email):
return {
"name": name,
"age": age,
"email": email,
"active": True
}
users = {}
users["john_doe"] = create_user_profile("John Doe", 30, "[email protected]")
users["jane_smith"] = create_user_profile("Jane Smith", 25, "[email protected]")
Mapping Nested Structures
raw_data = [
{"id": 1, "name": "Product A", "price": 100},
{"id": 2, "name": "Product B", "price": 200}
]
product_map = {item['id']: item['name'] for item in raw_data}
price_map = {item['id']: item['price'] for item in raw_data}
print(product_map) ## {1: 'Product A', 2: 'Product B'}
print(price_map) ## {1: 100, 2: 200}
3. Counting and Grouping
Word Frequency Analysis
def count_word_frequency(text):
words = text.lower().split()
frequency = {}
for word in words:
frequency[word] = frequency.get(word, 0) + 1
return frequency
sample_text = "python is awesome python is powerful"
word_counts = count_word_frequency(sample_text)
print(word_counts)
4. Configuration Management
class ConfigManager:
def __init__(self):
self.config = {
"database": {
"host": "localhost",
"port": 5432,
"username": "admin"
},
"logging": {
"level": "INFO",
"file": "/var/log/app.log"
}
}
def get_config(self, section, key):
return self.config.get(section, {}).get(key)
config = ConfigManager()
db_host = config.get_config("database", "host")
Mapping Workflow
graph TD
A[Input Data] --> B{Mapping Strategy}
B -->|Transformation| C[Processed Dictionary]
B -->|Filtering| D[Filtered Dictionary]
B -->|Aggregation| E[Aggregated Results]
Advanced Mapping Techniques
Nested Dictionary Manipulation
def deep_update(base_dict, update_dict):
for key, value in update_dict.items():
if isinstance(value, dict):
base_dict[key] = deep_update(base_dict.get(key, {}), value)
else:
base_dict[key] = value
return base_dict
base = {"user": {"name": "John", "age": 30}}
update = {"user": {"email": "[email protected]"}}
result = deep_update(base, update)
Technique |
Time Complexity |
Use Case |
dict comprehension |
O(n) |
Simple transformations |
.get() method |
O(1) |
Safe key access |
Nested mapping |
O(n*m) |
Complex transformations |
Best Practices
- Use meaningful keys
- Handle potential KeyError
- Choose appropriate mapping strategy
- Consider performance for large datasets
Mastering these practical mapping techniques will enhance your Python skills in LabEx programming courses.