Did you know you can create a dictionary in Python where a single key maps to multiple values? This can be useful in many situations, such as grouping students by class, products by category, or names by country. The easiest and most efficient way to do this is by using defaultdict
from the collections
module.
What is defaultdict
?
A defaultdict
is a variation of Python’s standard dictionary that allows you to define a default value for non-existent keys. When you access a key that doesn’t yet exist, it automatically creates that key with the default value you specified.
Creating a dictionary of lists
Imagine you want to store student names by class. Here’s how to create this type of dictionary:
from collections import defaultdict
students_by_class = defaultdict(list)
Now all keys in students_by_class
will automatically map to an empty list by default:
print(students_by_class["Class A"]) # []
print(students_by_class["Class B"]) # []
Adding multiple values to a single key
Let’s add students to each class:
students_by_class["Class A"].append("Anna")
students_by_class["Class A"].append("Carlos")
students_by_class["Class B"].append("Bruno")
print(students_by_class["Class A"]) # ['Anna', 'Carlos']
print(students_by_class["Class B"]) # ['Bruno']
Notice how we can add multiple names to the same key, and everything works smoothly even if the key didn’t exist before.
Another example: products by category
products_by_category = defaultdict(list)
products_by_category["Electronics"].append("Smartphone")
products_by_category["Electronics"].append("Laptop")
products_by_category["Clothing"].append("T-shirt")
print(products_by_category["Electronics"]) # ['Smartphone', 'Laptop']
print(products_by_category["Clothing"]) # ['T-shirt']
Conclusion
defaultdict
is a powerful tool when dealing with grouped collections. It saves you from having to check if a key exists before adding a new value, making your code cleaner and more readable.
Try it yourself and see how much easier it becomes to work with dictionaries in Python!
Copyright Notice: Unless otherwise indicated, all articles are original to this site, and reproduction must cite the source
Article link:http://pybeginners.com/article/multi-value-dictionary-in-python/