Dictionary Methods

get, keys, values, items, update

Interview Relevant: Essential methods

Dictionary Methods

Common dictionary manipulation methods.

Code Examples

Dictionary methods for manipulation.

python
1d = {"a": 1, "b": 2, "c": 3}
2
3# Keys, values, items
4d.keys()    # dict_keys(['a', 'b', 'c'])
5d.values()  # dict_values([1, 2, 3])
6d.items()   # dict_items([('a', 1), ...])
7
8# Get with default
9d.get("x", 0)  # 0 (key doesn't exist)
10
11# setdefault (get or set if missing)
12d.setdefault("x", 10)  # Returns 10, adds to dict
13
14# Update (merge dictionaries)
15d.update({"c": 30, "d": 4})
16d |= {"e": 5}  # Python 3.9+
17
18# Pop
19val = d.pop("a")       # Remove and return
20val = d.pop("z", None) # Default if missing
21
22# popitem (remove last inserted)
23key, val = d.popitem()
24
25# Clear
26d.clear()
27
28# Copy
29d2 = d.copy()  # Shallow copy

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In