-
-
Notifications
You must be signed in to change notification settings - Fork 596
Expand file tree
/
Copy pathdefaultdict.py
More file actions
63 lines (46 loc) · 2.16 KB
/
Copy pathdefaultdict.py
File metadata and controls
63 lines (46 loc) · 2.16 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
"""
A `collections.defaultdict` is a subclass of the built-in dictionary (`dict`)
that automatically initializes missing keys with a default value.
It overrides the `__missing__` method and calls a user-specified factory
function (e.g., `list`, `int`, `set`) to provide a default value when a key
is accessed but not found. This eliminates the need for boilerplate checks
using `dict.setdefault()` or `if key not in dict` blocks, improving both
readability and efficiency.
"""
from collections import defaultdict
# Module-level constants
_GPA_MIN = 0.0
_GPA_MAX = 4.0
_EPS = 0.000001
def main() -> None:
# Let's create a defaultdict with student keys and GPA values. The first
# parameter is called default_factory, and it is the initialization value for
# first use of a key. It can be a common type or a function
student_gpa = defaultdict(float, [("john", 3.5), ("bob", 2.8), ("mary", 3.2)])
# There are three student records in this dictionary
assert len(student_gpa) == 3
# Each student has a name key and a GPA value
assert len(student_gpa.keys()) == len(student_gpa.values())
# We can get the names in isolation. Note that in Python 3.7 and
# above, dictionary entries are sorted in the order that they were
# defined or inserted
student_names = []
for student in student_gpa.keys():
student_names.append(student)
assert student_names == ["john", "bob", "mary"]
# We can get the GPA for a specific student
assert abs(student_gpa["john"] - 3.5) < _EPS
# And the defaultdict allow us to get the GPA of a student that is not in
# the data structure yet, returning a default value for float that is 0.0
assert student_gpa["jane"] == _GPA_MIN
# And now there are four student records in this dictionary
assert len(student_gpa) == 4
# You can set the default value in default_factory attribute
def set_default_to_gpa_max() -> float:
return _GPA_MAX
student_gpa.default_factory = set_default_to_gpa_max
assert student_gpa["rika"] == _GPA_MAX
# And now there are five student records in this dictionary
assert len(student_gpa) == 5
if __name__ == "__main__":
main()