Practical Examples and Applications
Now that you have a solid understanding of Python dictionaries and efficient techniques for value mapping, let's explore some practical examples and applications.
Data Aggregation and Grouping
Suppose you have a list of student records, each containing a student's name, grade, and subject. You want to create a dictionary that groups the students by their subjects, with the values being lists of their names and grades.
student_records = [
{"name": "John", "grade": 85, "subject": "Math"},
{"name": "Jane", "grade": 92, "subject": "Math"},
{"name": "Bob", "grade": 78, "subject": "English"},
{"name": "Alice", "grade": 88, "subject": "English"},
{"name": "Tom", "grade": 90, "subject": "Math"},
]
subject_students = {}
for record in student_records:
subject = record["subject"]
if subject not in subject_students:
subject_students[subject] = []
subject_students[subject].append((record["name"], record["grade"]))
print(subject_students)
## Output: {'Math': [('John', 85), ('Jane', 92), ('Tom', 90)], 'English': [('Bob', 78), ('Alice', 88)]}
Frequency Analysis and Counting
You can use dictionaries to perform frequency analysis on a set of data. For example, let's count the occurrences of each word in a given text.
text = "The quick brown fox jumps over the lazy dog. The dog barks at the fox."
word_count = {}
for word in text.lower().split():
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
print(word_count)
## Output: {'the': 3, 'quick': 1, 'brown': 1, 'fox': 2, 'jumps': 1, 'over': 1, 'lazy': 1, 'dog': 2, 'barks': 1, 'at': 1}
Lookup Tables and Configuration Management
Dictionaries can be used as lookup tables to store and retrieve configuration settings, mapping of codes to descriptions, or any other key-value data.
## Example: Mapping country codes to country names
country_codes = {
"USA": "United States of America",
"CAN": "Canada",
"GBR": "United Kingdom",
"AUS": "Australia",
"IND": "India",
}
country_code = "GBR"
country_name = country_codes.get(country_code, "Unknown")
print(country_name) ## Output: United Kingdom
These examples demonstrate how you can leverage the power of Python dictionaries to solve a variety of real-world problems. The flexibility and efficiency of dictionaries make them a versatile tool in your Python programming toolkit.