Q:

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
1
>>> 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
>>>
2
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
...     d[k].append(v)
...
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
0

New to Communities?

Join the community