-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdict.py
More file actions
77 lines (61 loc) · 1.75 KB
/
dict.py
File metadata and controls
77 lines (61 loc) · 1.75 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
69
70
71
72
73
74
75
76
77
student = {
"name": "Sara",
"age": 20,
"courses": ["Math", "Physics"]
}
print("Original dict:", student)
# Access value by key
print("Name:", student["name"])
# Add new key
student["grade"] = "A"
print("After adding grade:", student)
# Change value
student["age"] = 21
print("After changing age:", student)
# Remove a key
del student["courses"]
print("After deleting 'courses':", student)
# Loop through dictionary
print("Loop through keys and values:")
for key, value in student.items():
print(f" {key} => {value}")
student_scores = {
"Alice": 85,
"Bob": 92,
"Charlie": 78,
"Diana": 90
}
print("Student scores:", student_scores)
# Access a value
print("Bob's score:", student_scores["Bob"])
# Add a new student
student_scores["Eve"] = 88
print("After adding Eve:", student_scores)
# Change a score
student_scores["Charlie"] = 82
print("After updating Charlie's score:", student_scores)
# Remove a student
del student_scores["Alice"]
print("After deleting Alice:", student_scores)
print("\nChecking performance:")
# Loop through and do if/else checks
for student, score in student_scores.items():
# conditional logic
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(f"{student}: Score = {score}, Grade = {grade}")
print("\nOther operations:")
# Check membership
print("Is 'Bob' in student_scores?", "Bob" in student_scores)
print("Is 95 in scores (values)?", 95 in student_scores.values())
# Get all keys, all values
keys = student_scores.keys()
values = student_scores.values()
print("All students:", list(keys))
print("All scores:", list(values))