defaultdict python 3 code example
Example 1: python defaultdict
>>> 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
>>>
Example 2: python defaultdict default value
d = defaultdict(lambda:1)
Example 3: defaultdict in python
>>> 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])]
Example 4: .defaultdict
>>> from collections import defaultdict
>>> food_list = 'spam spam spam spam spam spam eggs spam'.split()
>>> food_count = defaultdict(int)
>>> for food in food_list:
... food_count[food] += 1
...
defaultdict(<type 'int'>, {'eggs': 1, 'spam': 7})
>>>
Example 5: defaultdict key exists
'in' is the intended way to test for the existence of a key in a dict.
d = {"key1": 10, "key2": 23}
if "key1" in d:
print("this will execute")
if "nonexistent key" in d:
print("this will not")
Example 6: defaultdict python
>>> from collections import defaultdict
>>> food_list = 'spam spam spam spam spam spam eggs spam'.split()
>>> food_count = defaultdict(int)
>>> for food in food_list:
... food_count[food] += 1
...
defaul