keyerror in python defaultdict
# Defaultdict is a useful way of populating a dictionary without having
# to check if the key already exists in the dictionary
# Basic syntax:
from collections import defaultdict
your_dict = defaultdict(data_type)
# Where:
# - data_type is the default empty data type that gets created if a
# key is passed to the dictionary that hasn't already been added
# Exmple usage 1:
your_dict = defaultdict(list) # Set default data type = list
your_dict["a"] = 1
your_dict["b"] = 2
your_dict["c"].append(3) # In a normal dict this would return KeyError
your_dict
--> {'a': 1, 'b': 2, 'c': [3]} # 3 added with default data type = list
# Exmple usage 2:
your_dict = defaultdict(set) # Set default data type = set
your_dict["a"] = 1
your_dict["b"] = 2
your_dict["c"].add(3)
your_dict
--> {'a': 1, 'b': 2, 'c': {3}}
# Exmple usage 2:
your_dict = defaultdict(float) # Set default data type = float
your_dict["a"] = 1
your_dict["b"] = 2
your_dict["c"]
your_dict
--> {'a': 1, 'b': 2, 'c': 0.0} # Calling a key that isn't in the
# dictionary results in the addition of that key populated with the
# default data type
>>> from collections import defaultdict
>>> ice_cream = defaultdict(lambda: 'Vanilla')
>>>
>>> ice_cream = defaultdict(lambda: 'Vanilla')
>>> ice_cream['Sarah'] = 'Chunky Monkey'
>>> ice_cream['Abdul'] = 'Butter Pecan'
>>> print ice_cream['Sarah']
Chunky Monkey
>>> print ice_cream['Joe']
Vanilla
>>>