I\'ve read the examples in python docs, but still can\'t figure out what this method means. Can somebody help? Here are two examples from the python docs
>
I think its best used in place of a switch case statement. Imagine if we have a switch case statement as below:
option = 1
switch(option) {
case 1: print '1st option'
case 2: print '2nd option'
case 3: print '3rd option'
default: return 'No such option'
}
There is no switch
case statements available in python. We can achieve the same by using defaultdict
.
from collections import defaultdict
def default_value(): return "Default Value"
dd = defaultdict(default_value)
dd[1] = '1st option'
dd[2] = '2nd option'
dd[3] = '3rd option'
print(dd[4])
print(dd[5])
print(dd[3])
It prints:
Default Value
Default Value
3rd option
In the above snippet dd
has no keys 4 or 5 and hence it prints out a default value which we have configured in a helper function. This is quite nicer than a raw dictionary where a KeyError
is thrown if key is not present. From this it is evident that defaultdict
more like a switch case statement where we can avoid a complicated if-elif-elif-else
blocks.
One more good example that impressed me a lot from this site is:
>>> from collections import defaultdict
>>> food_list = 'spam spam spam spam spam spam eggs spam'.split()
>>> food_count = defaultdict(int) # default value of int is 0
>>> for food in food_list:
... food_count[food] += 1 # increment element's value by 1
...
defaultdict(, {'eggs': 1, 'spam': 7})
>>>
If we try to access any items other than eggs
and spam
we will get a count of 0.