Lesson 12
Dictionary Methods — get(), keys(), values(), items(), update()
Access and mutate Python dictionaries safely using get(), iterate with keys/values/items, merge with update(), and remove with pop() and popitem().
What you will learn
Safe access with get() · Iterate with keys(), values(), items() · Merge using update() · Remove using pop() and popitem()
Access and mutate Python dictionaries safely using the most important built-in methods. Learn safe lookups, iteration, bulk updates, and removal patterns.
| Method family | Role |
|---|---|
get() |
Safe lookup with defaults |
keys() / values() / items() |
Live views for iteration |
update() |
Merge mappings in place |
pop() / popitem() |
Remove and return values |
After File 11 — Frozenset Methods, you know hashable immutable sets. Dictionaries are the next major collection — key → value mappings you will use everywhere.
Learning roadmap
Dictionary = key → value mapping
A dictionary stores data as key-value pairs. Unlike lists, values are accessed by keys instead of indexes.
Every key must be unique; multiple keys can point to different values.
student = {
"name": "RS",
"age": 20,
"city": "HYD"
}
print(student["name"]) # RSType intro: dict — Key-Value Mapping.
1. Bracket access vs get()
Choosing the correct access method prevents unexpected crashes.
| Method | If key is missing |
|---|---|
d["key"] |
Raises KeyError |
d.get("key") |
Returns None |
d.get("key", 0) |
Returns the default value |
Unsafe
d = {"a": 1}
print(d["b"]) # KeyErrorSafe
d = {"a": 1}
print(d.get("b", 0)) # 0Try it in the playground
d = {"name": "RS", "age": 20, "city": "HYD"}
print(d.get("grade", "N/A")) # N/A — key does not existEquivalent to: d.get("grade", "N/A")
2. keys(), values(), and items()
These methods return views that reflect the dictionary's current contents.
| Method | Returns |
|---|---|
keys() |
All keys |
values() |
All values |
items() |
(key, value) tuples |
student = {
"name": "RS",
"age": 20,
"city": "HYD"
}
for key in student.keys():
print(key)
for value in student.values():
print(value)
for key, value in student.items():
print(f"{key} → {value}")Output:
name → RS
age → 20
city → HYDMost common interview pattern:
for key, value in d.items():
Views are dynamic — if you add or remove keys, the view updates automatically.
3. update() — merge dictionaries
update() modifies the existing dictionary. Existing keys are overwritten; new keys are added.
student = {"name": "RS", "age": 20, "city": "HYD"}
student.update({
"age": 21,
"grade": "A"
})
print(student)
# {'name': 'RS', 'age': 21, 'city': 'HYD', 'grade': 'A'}You can also pass keyword arguments:
d = {"a": 1}
d.update(b=2, c=3)4. pop() vs popitem()
pop(key)
Removes a specific key and returns its value.
d = {"name": "RS", "age": 20, "city": "HYD"}
value = d.pop("city")
print(value) # HYD
print(d) # {'name': 'RS', 'age': 20}Raises KeyError if the key is missing (unless you pass a default: pop(key, default)).
popitem()
Removes the last inserted key-value pair (Python 3.7+ insertion order).
d = {"name": "RS", "age": 20, "grade": "A"}
pair = d.popitem()
print(pair) # ('grade', 'A')| Method | Removes | Returns |
|---|---|---|
pop(key) |
Specific key | Value |
popitem() |
Last inserted pair | (key, value) tuple |
5. clear() and copy()
d = {1: "a", 2: "b"}
d.clear()
print(d) # {}copy() creates a shallow copy. The outer dictionary is new, but nested mutable objects are still shared.
original = {
1: [10, 20]
}
shallow = original.copy()
shallow[1].append(99)
print(original)
# {1: [10, 20, 99]}Rule:
dict.copy()is shallow. Usecopy.deepcopy()when nested objects must be completely independent.
Method cheat sheet
| Method | Purpose |
|---|---|
get(k, default) |
Safe value lookup |
keys() |
View all keys |
values() |
View all values |
items() |
View (key, value) pairs |
update() |
Merge another mapping |
pop(key) |
Remove one key and return value |
popitem() |
Remove last inserted pair |
clear() |
Empty the dictionary |
copy() |
Create a shallow copy |
Mini project — student profile
Build a student profile and print every field using items().
profile = {
"name": "RS",
"roll": 101,
"branch": "CSE"
}
profile["email"] = profile.get(
"email",
"not-set@school.edu"
)
for key, value in profile.items():
print(key, "→", value)Expected output:
name → RS
roll → 101
branch → CSE
email → not-set@school.eduCommon interview mistakes
Mistake 1 — using [] when the key might be missing:
# KeyError if "score" absent
# score = student["score"]
score = student.get("score", 0) # safeMistake 2 — thinking keys() returns a list:
d = {"a": 1}
view = d.keys() # dict_keys view — not a list
keys_list = list(d.keys())Mistake 3 — expecting popitem() to remove the first item:
# Python 3.7+ — popitem() removes LAST inserted (LIFO)
d = {"a": 1, "b": 2}
print(d.popitem()) # ('b', 2)Mistake 4 — shallow copy surprise with nested dicts:
import copy
original = {"meta": {"version": 1}}
safe = copy.deepcopy(original)Practice questions
Test yourself before File 13 — Nested Dictionaries:
- Which method safely returns a default instead of raising
KeyError? - What does
items()return for each element? - After
d.update({"b": 99}), what happens to an existing keyb? - Does
popitem()remove the first or last inserted pair? - Why does mutating a nested list inside a copied dict affect the original?
Knowledge check
Q1: Which method safely returns a default value instead of raising KeyError?
Answer: d.get("key", 0) — not d["key"] or d.pop("key") (pop removes).
Q2: Does popitem() remove the first inserted item?
Answer: No. In Python 3.7+, popitem() removes the last inserted key-value pair (LIFO behavior).
Q3: Best loop pattern for keys and values together?
Answer: for key, value in d.items():
Q4: What does update() do to existing keys?
Answer: Overwrites their values in place.
Q5: Is copy() deep or shallow?
Answer: Shallow — nested mutable objects are shared.
Key takeaways
- Use
get()for safe dictionary lookups. - Use
items()when you need both keys and values in a loop. - Use
update()to merge dictionaries in place. - Use
pop()for a specific key andpopitem()for the last inserted pair. - Remember:
copy()is shallow for nested objects.
Loading playground…