-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdict_key_value_item_get_examples.py
More file actions
66 lines (52 loc) · 1.87 KB
/
Copy pathdict_key_value_item_get_examples.py
File metadata and controls
66 lines (52 loc) · 1.87 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
# FAMOUS DICTIONARY EXAMPLES USING: get(), keys(), values(), items()
student = {
"name": "Alice",
"age": 21,
"major": "Computer Science",
"grade": "A"
}
# --------------------------------------------
# 1. .get() – Safe value access
# → Famous for avoiding KeyError if the key doesn't exist
# GOOD: get() returns default instead of crashing
print("Country:", student.get("country", "Not specified")) # Not specified
# BAD: This would raise KeyError
# print(student["country"])
# --------------------------------------------
# 2. .keys() – Useful for looping or checking presence
print("Keys in student dict:")
for key in student.keys():
print("-", key)
# Check if "age" is a key
if "age" in student.keys():
print("Yes, 'age' is a key.")
# --------------------------------------------
# 3. .values() – Check or search values
print("Values in student dict:")
for value in student.values():
print("-", value)
# Check if a specific value exists
if "Computer Science" in student.values():
print("Found the major!")
# --------------------------------------------
# 4. .items() – Iterate over both key and value (most common in loops)
print("Student Info:")
for key, value in student.items():
print(f"{key} → {value}")
# --------------------------------------------
# BONUS: Use in condition
if "grade" in student:
if student["grade"] == "A":
print("Excellent student!")
# --------------------------------------------
# 5. Finding Key from Value (reverse lookup)
# Let's say we want the key for value "A"
target_value = "A"
# Using a loop to search for matching value
for key, value in student.items():
if value == target_value:
print(f"Key for value '{target_value}' is: {key}")
# --------------------------------------------
# 6. Finding Value from Key (already known way)
# Just standard access
print("Grade is:", student["grade"]) # A