-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdefaultdict_module.py
More file actions
68 lines (48 loc) · 1.39 KB
/
Copy pathdefaultdict_module.py
File metadata and controls
68 lines (48 loc) · 1.39 KB
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
""" Defaultdict samples """
""" Define the 'Anonymous' string as default value for any requested key on a dictionary if non-existent """
from collections import defaultdict
def generate_defaultdict():
''' PS : use python -m doctest ./defaultdict.py to run it
:return:
>>> datastructure = generate_defaultdict()
>>> datastructure[3] = "John"
>>> print(datastructure[3])
John
>>> print(datastructure[9762])
Anonymous
>>> print(datastructure["pistache"])
Anonymous
'''
obj = defaultdict(lambda:"Anonymous")
return obj
""" Might also be done with a simple dict and a class """
class My_Dict(dict):
def __getitem__(self, key):
return self.get(key, "Anonymous")
def generate_my_dict():
''' PS : use python -m doctest ./defaultdict.py to run it
:return:
>>> datastructure = generate_my_dict()
>>> datastructure[3] = "John"
>>> print(datastructure[3])
John
>>> print(datastructure[9762])
Anonymous
>>> print(datastructure["pistache"])
Anonymous
'''
obj = My_Dict()
return obj
""" Counts the number of employees in each department """
from collections import defaultdict
dep = [
('Sales', 'John'),
('Sales', 'Martin'),
('Accounting', 'Jane'),
('Marketing', 'Elizabeth'),
('Marketing', 'Adam')
]
dd = defaultdict(int)
for department, _ in dep:
dd[department] += 1
print(dd)