← Back to Python, page 2

python-0023 · Easy fresher

What are the useful dictionary methods for safe lookups and updates?

d[key] raises KeyError when the key is missing, while d.get(key, default) returns a default. setdefault inserts a default if missing and returns the value, and the | operator (Python 3.9+) merges dicts into a new one, with the right side winning. Iterate with .items() to get keys and values together.

Full answer
python
stock = {"pen": 10, "ink": 0}
print(stock.get("pad"), stock.get("pad", 0))
try:
    stock["pad"]
except KeyError as e:
    print("KeyError:", e)
stock.setdefault("pad", 5)
stock.setdefault("pen", 99)
print(stock)
print(stock | {"pen": 12, "cap": 3})
for item, qty in stock.items():
    if qty == 0:
        print("out of stock:", item)
print(stock.pop("ink"), list(stock))

Output:

text
None 0
KeyError: 'pad'
{'pen': 10, 'ink': 0, 'pad': 5}
{'pen': 12, 'ink': 0, 'pad': 5, 'cap': 3}
out of stock: ink
0 ['pen', 'pad']

get returns None or the given default for 'pad' without raising. setdefault added 'pad' but left 'pen' unchanged because it already existed. The merge with | created a new dict where 'pen' took the right-hand value, while stock itself is unchanged until assigned (|= updates in place). pop removes a key and returns its value. Dicts keep insertion order, which the printed key list shows.

python
stock = {"pen": 10, "ink": 0}
print(stock.get("pad"), stock.get("pad", 0))
try:
    stock["pad"]
except KeyError as e:
    print("KeyError:", e)
stock.setdefault("pad", 5)
stock.setdefault("pen", 99)
print(stock)
print(stock | {"pen": 12, "cap": 3})
for item, qty in stock.items():
    if qty == 0:
        print("out of stock:", item)
print(stock.pop("ink"), list(stock))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • get avoids KeyError
  • setdefault inserts only if missing
  • | merges, right side wins
  • items() yields pairs
  • Dicts keep insertion order

Common mistakes

  • Checking 'if key in d' then indexing, twice the lookups
  • Modifying a dict while iterating over it

Follow-ups

  • When would defaultdict be better than setdefault?
  • What happens if a dict changes size during iteration?

Tips

  • Show a missing key both ways