Skip to main content
MahiDev — Learn. Build. Become AI-ready.

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().

Intermediate28 min

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

get views update pop dictionary methods roadmap

Dictionary = key → value mapping

A dictionary stores data as key-value pairs. Unlike lists, values are accessed by keys instead of indexes.

Dictionary key value mapping name age city

Every key must be unique; multiple keys can point to different values.

python
student = {
    "name": "RS",
    "age": 20,
    "city": "HYD"
}

print(student["name"])   # RS

Type intro: dict — Key-Value Mapping.

1. Bracket access vs get()

Choosing the correct access method prevents unexpected crashes.

Bracket KeyError vs get with default
Method If key is missing
d["key"] Raises KeyError
d.get("key") Returns None
d.get("key", 0) Returns the default value

Unsafe

python
d = {"a": 1}
print(d["b"])   # KeyError

Safe

python
d = {"a": 1}
print(d.get("b", 0))   # 0

Try it in the playground

python
d = {"name": "RS", "age": 20, "city": "HYD"}
print(d.get("grade", "N/A"))   # N/A — key does not exist

Equivalent to: d.get("grade", "N/A")

2. keys(), values(), and items()

These methods return views that reflect the dictionary's current contents.

keys values items three-column view diagram
Method Returns
keys() All keys
values() All values
items() (key, value) tuples
python
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:

text
name → RS
age → 20
city → HYD

Most 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.

update before merge after diagram
python
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:

python
d = {"a": 1}
d.update(b=2, c=3)

4. pop() vs popitem()

pop key vs popitem last inserted

pop(key)

Removes a specific key and returns its value.

python
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).

python
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()

python
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.

Shallow copy shares nested list reference
python
original = {
    1: [10, 20]
}

shallow = original.copy()
shallow[1].append(99)

print(original)
# {1: [10, 20, 99]}

Rule: dict.copy() is shallow. Use copy.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().

python
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:

text
name → RS
roll → 101
branch → CSE
email → not-set@school.edu
Student profile built with get and items loop

Common interview mistakes

Mistake 1 — using [] when the key might be missing:

python
# KeyError if "score" absent
# score = student["score"]
score = student.get("score", 0)   # safe

Mistake 2 — thinking keys() returns a list:

python
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
# 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:

python
import copy
original = {"meta": {"version": 1}}
safe = copy.deepcopy(original)

Practice questions

Test yourself before File 13 — Nested Dictionaries:

  1. Which method safely returns a default instead of raising KeyError?
  2. What does items() return for each element?
  3. After d.update({"b": 99}), what happens to an existing key b?
  4. Does popitem() remove the first or last inserted pair?
  5. 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 and popitem() for the last inserted pair.
  • Remember: copy() is shallow for nested objects.

Loading playground…