defaultdict python
# 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
>>>
# Python program to demonstrate
# defaultdict
from collections import defaultdict
# Function to return a default
# values for keys that is not
# present
def def_value():
return "Not Present"
# Defining the dict
d = defaultdict(def_value)
d["a"] = 1
d["b"] = 2
print(d["a"])
print(d["b"])
print(d["c"])
# Python program to demonstrate
# defaultdict
from collections import defaultdict
# Defining the dict
d = defaultdict(int)
L = [1, 2, 3, 4, 2, 4, 1, 2]
# Iterate through the list
# for keeping the count
for i in L:
# The default value is 0
# so there is no need to
# enter the key first
d[i] += 1
print(d)