forked from INM-6/Python-Module-of-the-Week
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DefaultDict.py
72 lines (57 loc) · 1.37 KB
/
DefaultDict.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
from collections import defaultdict
from pprint import pprint
Pizza_Ingredients = [
'tomatoes',
'flour',
'water',
'mozzarella',
'pineapple',
'tomatoes',
'paella',
]
# typical dict-stuff:
def oldschool_count():
count = {}
for ingredient in Pizza_Ingredients:
if ingredient not in count.keys():
count[ingredient] = 0
count[ingredient] += 1
pprint(count)
def oldschool_cluster():
length = {}
for ingredient in Pizza_Ingredients:
l = len(ingredient)
try:
length[l].append(ingredient)
except KeyError:
length[l] = [ingredient]
pprint(length)
# A bit nicer:
def count_via_get():
count = {}
for ingredient in Pizza_Ingredients:
count[ingredient] = count.get(ingredient, 0) + 1
pprint(count)
# now with neat defaultdicts:
def defaultdict_count():
count = defaultdict(int)
for ingredient in Pizza_Ingredients:
count[ingredient] += 1
pprint(dict(count))
def defaultdict_cluster():
length = defaultdict(list)
for ingredient in Pizza_Ingredients:
length[len(ingredient)].append(ingredient)
pprint(dict(length))
# defaultdict can take arbitrary generators:
def f():
return 2
d = defaultdict(f)
d[1] = 2
d[2]
print(dict(d))
d2 = defaultdict(lambda: defaultdict(list))
d2[1][2].append(3)
print(dict(d2))
"""
"""