Practical Examples
Real-World Dictionary Applications
Dictionaries are versatile data structures with numerous practical applications across various domains of programming.
1. Student Grade Management System
class GradeTracker:
def __init__(self):
self.students = {}
def add_student(self, name, grades):
self.students[name] = grades
def calculate_average(self, name):
return sum(self.students[name]) / len(self.students[name])
def get_top_performers(self, threshold=85):
return {
name: avg for name, avg in
[(name, sum(grades)/len(grades)) for name, grades in self.students.items()]
if avg >= threshold
}
## Usage example
tracker = GradeTracker()
tracker.add_student("Alice", [85, 90, 92])
tracker.add_student("Bob", [75, 80, 82])
tracker.add_student("Charlie", [90, 95, 93])
2. Word Frequency Counter
def count_word_frequency(text):
## Remove punctuation and convert to lowercase
words = text.lower().split()
frequency = {}
for word in words:
frequency[word] = frequency.get(word, 0) + 1
return frequency
## Example usage
sample_text = "python is awesome python is powerful"
word_freq = count_word_frequency(sample_text)
print(word_freq)
3. Configuration Management
class ConfigManager:
def __init__(self, default_config=None):
self.config = default_config or {}
def update_config(self, **kwargs):
self.config.update(kwargs)
def get_config(self, key, default=None):
return self.config.get(key, default)
## Usage
config = ConfigManager({"debug": False, "log_level": "INFO"})
config.update_config(debug=True, max_connections=100)
Practical Iteration Scenarios
Merging Dictionaries
## Multiple ways to merge dictionaries
def merge_dictionaries(dict1, dict2):
## Method 1: Using update()
merged = dict1.copy()
merged.update(dict2)
## Method 2: Using ** unpacking (Python 3.5+)
## merged = {**dict1, **dict2}
return merged
Dictionary Use Case Comparison
Scenario |
Best Dictionary Technique |
Key Considerations |
Data Caching |
.get() with default |
Prevent KeyError |
Configuration |
.update() method |
Flexible updates |
Frequency Count |
Increment with .get() |
Default value handling |
Advanced Pattern: Nested Dictionaries
def organize_inventory(items):
inventory = {}
for item in items:
category = item['category']
if category not in inventory:
inventory[category] = []
inventory[category].append(item['name'])
return inventory
## Example usage
items = [
{'name': 'Laptop', 'category': 'Electronics'},
{'name': 'Desk', 'category': 'Furniture'},
{'name': 'Smartphone', 'category': 'Electronics'}
]
organized = organize_inventory(items)
Workflow of Dictionary Processing
graph TD
A[Raw Data] --> B{Dictionary Transformation}
B --> C[Key Processing]
B --> D[Value Manipulation]
B --> E[Filtering/Mapping]
E --> F[Final Result]
Best Practices
- Use dictionaries for key-value mappings
- Leverage built-in dictionary methods
- Handle potential exceptions
- Choose appropriate iteration techniques
LabEx recommends exploring these practical examples to enhance your Python dictionary skills and develop robust, efficient solutions.