-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdefaultdict.py
More file actions
63 lines (41 loc) · 1.57 KB
/
defaultdict.py
File metadata and controls
63 lines (41 loc) · 1.57 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
# defaultdict — a dictionary that returns a default value for missing keys.
#
# Normally, accessing a missing key raises a KeyError.
# defaultdict takes a factory function; when a missing key is accessed,
# it calls the factory to create a default value automatically.
from collections import defaultdict
# --- Standard dict — KeyError on missing key ---
d = {1: 'apple', 2: 'banana', 3: 'cherry'}
print('Standard dict:')
print(d[1])
try:
print(d[4])
except KeyError:
print('KeyError: key 4 not found')
# --- defaultdict with None default ---
print('\ndefaultdict (default None):')
dd = defaultdict(lambda: None)
dd['a'] = 1
dd['b'] = 2
print(dd['a']) # 1
print(dd['b']) # 2
print(dd['c']) # None — key created automatically, no error
print(dict(dd)) # {'a': 1, 'b': 2, 'c': None}
# --- defaultdict with list default ---
# Useful for grouping values by key without checking if the key exists.
print('\ndefaultdict (default list) — grouping words by first letter:')
words = ['apple', 'banana', 'avocado', 'blueberry', 'cherry', 'apricot']
grouped = defaultdict(list)
for word in words:
grouped[word[0]].append(word)
for letter, group in sorted(grouped.items()):
print(f' {letter}: {group}')
# --- defaultdict with int default ---
# Useful for counting without initialising counts to 0.
print('\ndefaultdict (default int) — word frequency count:')
sentence = 'the cat sat on the mat the cat'
counts = defaultdict(int)
for word in sentence.split():
counts[word] += 1
for word, count in sorted(counts.items()):
print(f' {word}: {count}')