forked from huangsam/ultimate-python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdefaultdict.py
More file actions
Latest commit
57 lines (41 loc) · 1.82 KB
/
Copy pathdefaultdict.py
File metadata and controls
57 lines (41 loc) · 1.82 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
"""
This module demonstrates the use of defaultdict, which is a dictionary that is
possible to set up a default value in its creation.
"""
fromcollectionsimportdefaultdict
# Module-level constants
_GPA_MIN=0.0
_GPA_MAX=4.0
_EPS=0.000001
defmain() ->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
assertlen(student_gpa) ==3
# Each student has a name key and a GPA value
assertlen(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= []
forstudentinstudent_gpa.keys():
student_names.append(student)
assertstudent_names== ["john", "bob", "mary"]
# We can get the GPA for a specific student
assertabs(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
assertstudent_gpa["jane"] ==_GPA_MIN
# And now there are four student records in this dictionary
assertlen(student_gpa) ==4
# You can set the default value in default_factory attribute
defset_default_to_gpa_max():
return_GPA_MAX
student_gpa.default_factory=set_default_to_gpa_max
assertstudent_gpa["rika"] ==_GPA_MAX
# And now there are five student records in this dictionary
assertlen(student_gpa) ==5
if__name__=="__main__":
main()