-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdict_methods_guid.py
More file actions
63 lines (53 loc) · 1.95 KB
/
Copy pathdict_methods_guid.py
File metadata and controls
63 lines (53 loc) · 1.95 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
# DICTIONARY METHODS – MOST IMPORTANT & COMMON
person = {
"name": "Alice",
"age": 22,
"country": "Germany"
}
# --------------------------------------------
# 1. get(key[, default])
# → Returns the value for the key if it exists; otherwise returns default (or None)
print("get('name'):", person.get("name")) # Alice
print("get('gender'):", person.get("gender")) # None
print("get('gender', 'Not specified'):", person.get("gender", "Not specified"))
# --------------------------------------------
# 2. keys()
# → Returns a view of all keys
print("Keys:", person.keys()) # dict_keys(['name', 'age', 'country'])
# --------------------------------------------
# 3. values()
# → Returns a view of all values
print("Values:", person.values()) # dict_values(['Alice', 22, 'Germany'])
# --------------------------------------------
# 4. items()
# → Returns a view of all key-value pairs as tuples
print("Items:", person.items()) # dict_items([('name', 'Alice'), ('age', 22), ...])
# --------------------------------------------
# 5. pop(key)
# → Removes a key and returns its value
age = person.pop("age")
print("Popped 'age':", age)
print("After pop():", person)
# --------------------------------------------
# 6. popitem()
# → Removes and returns the last inserted (key, value) pair
last_item = person.popitem()
print("Popped last item:", last_item)
print("After popitem():", person)
# --------------------------------------------
# 7. update(other_dict)
# → Merges another dictionary into current one
person.update({"name": "Bob", "gender": "Male"})
print("After update():", person)
# --------------------------------------------
# 8. clear()
# → Removes all key-value pairs from dictionary
temp = {"x": 1, "y": 2}
temp.clear()
print("After clear():", temp)
# --------------------------------------------
# 9. copy()
# → Returns a shallow copy of the dictionary
original = {"a": 1, "b": 2}
duplicate = original.copy()
print("Copy:", duplicate)