Skip to content

Demystifying default dict: Simplify Your Python Code

[

Using the Python defaultdict Type for Handling Missing Keys

A common problem that you can face when working with Python dictionaries is to try to access or modify keys that don’t exist in the dictionary. This will raise a KeyError and break up your code execution. To handle these kinds of situations, the standard library provides the Python defaultdict type, a dictionary-like class that’s available for you in collections.

The Python defaultdict type behaves almost exactly like a regular Python dictionary, but if you try to access or modify a missing key, then defaultdict will automatically create the key and generate a default value for it. This makes defaultdict a valuable option for handling missing keys in dictionaries.

How to use the Python defaultdict Type for Handling Missing Keys in a Dictionary

Let’s take a look at some practical examples to understand how the Python defaultdict type can be used to handle missing keys in dictionaries.

Grouping Items

One common use case for defaultdict is when you want to group items based on a specific key. Here’s an example:

from collections import defaultdict
fruits = [('apple', 2), ('banana', 3), ('apple', 5), ('banana', 1), ('orange', 4)]
# Create a defaultdict with a list as the default value
fruit_groups = defaultdict(list)
# Group the items based on the fruit type
for fruit, quantity in fruits:
fruit_groups[fruit].append(quantity)
# Print the grouped items
for fruit, quantities in fruit_groups.items():
print(fruit, quantities)

Output:

apple [2, 5]
banana [3, 1]
orange [4]

In this example, we have a list of tuples representing fruits and their quantities. We create a defaultdict with a list as the default value. Then, we iterate over the list of fruits and use the fruit as the key to access the defaultdict. If the fruit key doesn’t exist, defaultdict automatically creates it and initializes it with an empty list. We then append the quantity to the list associated with the fruit. Finally, we print the grouped items.

Grouping Unique Items

If you want to group unique items, you can use a defaultdict with a set as the default value. Here’s an example:

from collections import defaultdict
fruits = ['apple', 'banana', 'apple', 'banana', 'orange']
# Create a defaultdict with a set as the default value
unique_fruits = defaultdict(set)
# Group the unique items
for fruit in fruits:
unique_fruits[fruit]
# Print the unique items
print(unique_fruits.keys())

Output:

dict_keys(['apple', 'banana', 'orange'])

In this example, we have a list of fruits. We create a defaultdict with a set as the default value. Then, we iterate over the list of fruits and use each fruit as the key to access the defaultdict. If the fruit key doesn’t exist, defaultdict automatically creates it and initializes it with an empty set. We don’t need to append or add any values, as the set automatically ensures that only unique items are stored. Finally, we print the unique fruits.

Counting Items

defaultdict can also be used to count the occurrence of items. Here’s an example:

from collections import defaultdict
fruits = ['apple', 'banana', 'apple', 'banana', 'orange']
# Create a defaultdict with an integer as the default value
fruit_counts = defaultdict(int)
# Count the occurrence of each fruit
for fruit in fruits:
fruit_counts[fruit] += 1
# Print the counts
for fruit, count in fruit_counts.items():
print(fruit, count)

Output:

apple 2
banana 2
orange 1

In this example, we have a list of fruits. We create a defaultdict with an integer as the default value. Then, we iterate over the list of fruits and use each fruit as the key to access the defaultdict. If the fruit key doesn’t exist, defaultdict automatically creates it and initializes it with 0. We then increment the count by 1 for each occurrence of the fruit. Finally, we print the fruit counts.

Accumulating Values

Another useful application of defaultdict is to accumulate values. Here’s an example:

from collections import defaultdict
fruits = [('apple', 2), ('banana', 3), ('apple', 5), ('banana', 1), ('orange', 4)]
# Create a defaultdict with an integer as the default value
total_quantity = defaultdict(int)
# Accumulate the total quantity for each fruit
for fruit, quantity in fruits:
total_quantity[fruit] += quantity
# Print the total quantity for each fruit
for fruit, quantity in total_quantity.items():
print(fruit, quantity)

Output:

apple 7
banana 4
orange 4

In this example, we have a list of tuples representing fruits and their quantities. We create a defaultdict with an integer as the default value. Then, we iterate over the list of fruits and use the fruit as the key to access the defaultdict. If the fruit key doesn’t exist, defaultdict automatically creates it and initializes it with 0. We then accumulate the quantity for each fruit. Finally, we print the total quantity for each fruit.

Conclusion

In this tutorial, you learned how to use the Python defaultdict type for handling missing keys in dictionaries. You saw how defaultdict can be used for grouping, grouping unique items, counting, and accumulating values. This powerful class can make your code more robust and efficient when working with dictionaries. Remember to check out the official Python documentation for more details on the defaultdict type. Happy coding!