-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathdefaultdict_tutorial.py
31 lines (24 loc) · 1.06 KB
/
defaultdict_tutorial.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
# defaultdict means that if a key is not found in the dictionary,
# then instead of a KeyError being thrown, a new entry is created.
# The type of this new entry is given by the argument of defaultdict.
from collections import defaultdict
def ex1():
# For the first example, default items are created using int(), which will return the integer object 0.
int_dict = defaultdict(int)
print('int_dict[3]', int_dict[3]) # print int(), thus 0
# For the second example, default items are created using list(), which returns a new empty list object.
list_dict = defaultdict(list)
print('list_dict[test]', list_dict['ok']) # print list(), thus []
# default
dic_list = defaultdict(lambda: 'test')
dic_list['name'] = 'twtrubiks'
print('dic_list[name]', dic_list['name'])
print('dic_list[sex]', dic_list['sex'])
def ex2_letter_frequency(sentence):
frequencies = defaultdict(int)
for letter in sentence:
frequencies[letter] += 1
return frequencies
if __name__ == "__main__":
ex1()
print(ex2_letter_frequency('sentence'))