defaultdict
is a subclass of the built-in dict
class from the collections
module. It provides a convenient way to handle missing keys by automatically assigning a default value when accessing a key that doesn't exist in the dictionary.
To use defaultdict
, you need to import it from the collections
module. Here's an example:
from collections import defaultdict fruit_prices = defaultdict(lambda: "Unknown") fruit_prices["apple"] = 1.0 fruit_prices["banana"] = 0.5 print(fruit_prices["apple"]) # Output: 1.0 print(fruit_prices["banana"]) # Output: 0.5 print(fruit_prices["orange"]) # Output: Unknown
In this code, we create a defaultdict
object called fruit_prices
with a default value of "Unknown"
. We assign prices for "apple"
and "banana"
, but when we access the price for "orange"
, which is not present in the dictionary, the default value "Unknown"
is returned.
The default value is specified as a lambda function in this example, but you can use any callable object e.g. list
, dict
or a function that doesn't require any arguments.
The benefit of using defaultdict
is that it eliminates the need for explicit checks and handling of missing keys. When accessing a missing key, it automatically creates the key with the default value assigned to it.