1# set default values for all keys
2d = collections.defaultdict(lambda:1)
3# set default value for a key if not exist
4value = d.get(key,default_value)
1>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
2>>> d = defaultdict(list)
3>>> for k, v in s:
4... d[k].append(v)
5...
6>>> d.items()
7[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
8
1>>> from collections import defaultdict
2>>> food_list = 'spam spam spam spam spam spam eggs spam'.split()
3>>> food_count = defaultdict(int) # default value of int is 0
4>>> for food in food_list:
5... food_count[food] += 1 # increment element's value by 1
6...
7defaultdict(<type 'int'>, {'eggs': 1, 'spam': 7})
8>>>
1>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
2>>> d = defaultdict(list)
3>>> for k, v in s:
4... d[k].append(v)
5...
6>>> d.items()
7[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
1>>> from collections import defaultdict
2>>> food_list = 'spam spam spam spam spam spam eggs spam'.split()
3>>> food_count = defaultdict(int) # default value of int is 0
4>>> for food in food_list:
5... food_count[food] += 1 # increment element's value by 1
6...
7defaul