Dictionary Methods Deep Dive

Published by Brayan K

Dictionary methods are the built-in functions every dict carries — like get, setdefault, update, pop, and items — that let you read, change, and combine key-value data safely without ever risking a crash from a missing key.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Choose what a missing key means

A fallback is a policy decision, not an automatic improvement. A missing optional note can reasonably become an empty string; a missing invoice total should usually be noticed. Despite the broad wording in the introduction, dictionary methods are not universally safe: pop without a default and ordinary bracket access can still raise KeyError.

settings = {"retries": 0, "note": None}
print(settings.get("retries", 3))
print(settings.get("retries") or 3)
print(settings.get("note", "no note"))
print(settings.get("missing", "no note"))
print("missing" in settings)

# ✅ Expected output:
# 0
# 3
# None
# no note
# False

get(key, default) uses the default only when the key is absent. The expression value or default instead replaces any false value, including a deliberately chosen zero. A stored None also remains None under get. When absence needs a distinct meaning, membership testing makes it explicit.

invoice = {"customer": "Asha"}
print(invoice["total"])

# ✅ Expected error:
# KeyError: 'total'

For optional data, invoice.get("note", "") supplies a fallback without modifying the invoice. For required data, validate the key or allow the error to identify a broken contract. Dictionaries in Python owns keys, hashing, and ordinary lookup; this lesson compares the methods you use to implement those policies.

setdefault inserts once and returns the stored value

groups = {}
for category, item in [("drink", "tea"), ("food", "rice"), ("drink", "coffee")]:
    groups.setdefault(category, []).append(item)
print(groups)
same = groups.setdefault("drink", ["water"])
print(same is groups["drink"])
print(groups["drink"])

# ✅ Expected output:
# {'drink': ['tea', 'coffee'], 'food': ['rice']}
# True
# ['tea', 'coffee']

On the first access, setdefault stores the default and returns it. On later accesses, it returns the existing value; it does not replace it. That value must support the operation you call. An existing None does not become a list simply because the default is a list.

groups = {"drink": None}
groups.setdefault("drink", []).append("tea")

# ✅ Expected error:
# AttributeError: 'NoneType' object has no attribute 'append'

Choose a consistent data shape when you create the mapping, or explicitly reject incompatible input before grouping. For repeated automatic group creation, Counter & defaultdict owns the factory-based alternative.

def make_default():
    print("default evaluated")
    return []

groups = {"drink": ["tea"]}
groups.setdefault("drink", make_default())
print(groups["drink"])

# ✅ Expected output:
# default evaluated
# ['tea']

Python evaluates call arguments before the method decides whether it needs them. If making a default is expensive or has side effects, check membership first or use an appropriate lazy factory. The same argument-evaluation rule applies to get; a fallback expression is not a deferred callback.

Merge precedence and return values are separate questions

defaults = {"theme": "light", "retries": 3}
overrides = {"retries": 0}
combined = defaults | overrides
print(combined)
print(defaults)
returned = defaults.update(overrides)
print(defaults)
print(returned)

# ✅ Expected output:
# {'theme': 'light', 'retries': 0}
# {'theme': 'light', 'retries': 3}
# {'theme': 'light', 'retries': 0}
# None

For duplicate keys, values from the right-hand mapping win. a | b makes a new dictionary; a.update(b) mutates a and returns None. Do not assign that return value back to your dictionary. Updating an existing key keeps its insertion position; a genuinely new key is appended.

settings = {"theme": "light"}
settings = settings.update({"theme": "dark"})
print(settings["theme"])

# ✅ Expected error:
# TypeError: 'NoneType' object is not subscriptable

Call settings.update(...) on its own, or use settings = settings | overrides when a new mapping is what you want. Neither operation recursively merges nested dictionaries. A nested value on the right replaces the corresponding value on the left.

A view follows the dictionary; a snapshot does not

stock = {"tea": 2}
keys = stock.keys()
snapshot = list(stock)
stock["coffee"] = 3
print(list(keys))
print(snapshot)
print(list(stock.items()))

# ✅ Expected output:
# ['tea', 'coffee']
# ['tea']
# [('tea', 2), ('coffee', 3)]

keys(), values(), and items() return views tied to the dictionary. Converting a view to a list makes a shallow snapshot of its entries at that moment. Views are iterable, not lists with positional indexing. Adding or removing dictionary entries while iterating that same dictionary is unsafe.

stock = {"tea": 0, "coffee": 3}
for name in stock:
    if stock[name] == 0:
        del stock[name]

# ✅ Expected error:
# RuntimeError: dictionary changed size during iteration
stock = {"tea": 0, "coffee": 3}
for name in list(stock):
    if stock[name] == 0:
        del stock[name]
print(stock)

# ✅ Expected output:
# {'coffee': 3}

For a larger transformation, construct a new dictionary instead of mutating the current iteration. Comprehensions owns that syntax; the point here is choosing between a live view and a stable iteration input.

New outer dictionaries can still share inner objects

bad = dict.fromkeys(["red", "blue"], [])
bad["red"].append("paint")
print(bad)
print(bad["red"] is bad["blue"])

good = {name: [] for name in ["red", "blue"]}
good["red"].append("paint")
print(good)
print(good["red"] is good["blue"])

# ✅ Expected output:
# {'red': ['paint'], 'blue': ['paint']}
# True
# {'red': ['paint'], 'blue': []}
# False

fromkeys is useful for one immutable starting value, such as zero. With a mutable value, it stores the same reference under every key. A comprehension evaluates the list expression once per key. Likewise, copy() makes a new outer dictionary but keeps references to nested objects; use deliberate copies at the levels your application must isolate.

original = {"tags": ["python"]}
copied = original.copy()
copied["tags"].append("testing")
print(original)
print(copied is original, copied["tags"] is original["tags"])

# ✅ Expected output:
# {'tags': ['python', 'testing']}
# False True

Remove a key while choosing an absence policy

settings = {"temporary": True, "theme": "dark"}
removed = settings.pop("temporary")
missing = settings.pop("debug", False)
print(removed, missing)
print(settings)
print(settings.popitem())
print(settings)

# ✅ Expected output:
# True False
# {'theme': 'dark'}
# ('theme', 'dark')
# {}

pop returns the removed value. Without a default, an absent key raises KeyError. popitem() removes the last inserted pair and raises KeyError on an empty dictionary; it is not a random-selection method. clear() empties a dictionary in place and returns None.

settings = {"retries": 3, "temporary": True}
override = {"retries": 0}
settings.___(override)
temporary = settings.pop("temporary", ___)
print(settings)
print(temporary)

# 👉 replace ___ with update
# 👉 replace ___ with False

# ✅ Expected output:
# {'retries': 0}
# True

Build settings without altering the defaults

Given defaults with retries: 3 and tags: ["base"], and overrides with retries: 0, build independent settings. Add the tag local only to the result, remove an optional debug flag with a false fallback, and print both dictionaries plus that flag. The nested tags list must not be shared. Keep the intentionally chosen zero.

defaults = {"retries": 3, "tags": ["base"]}
overrides = {"retries": 0}
settings = defaults | overrides
settings["tags"] = list(settings["tags"])
settings["tags"].append("local")
debug = settings.pop("debug", False)
print(defaults)
print(settings)
print(debug)

# ✅ Expected output:
# {'retries': 3, 'tags': ['base']}
# {'retries': 0, 'tags': ['base', 'local']}
# False

This solution assumes tags is a list of strings. If overrides can replace it with another type, validate that boundary before copying or appending. The dictionary reference specifies the individual method contracts; your application still chooses which data shapes it accepts.

Practice quiz

What does this program print? d = {"limit": 0} print(d.get("limit", 5), d.get("limit") or 5)

  • 0 5
  • 5 5
  • 0 0
  • 5 0

Answer: 0 5. get falls back only on absence; or also replaces zero.

What does this program print? d = {"x": None} print(d.setdefault("x", [])) print(d)

  • [] {'x': []}
  • None {}
  • None {'x': None}
  • [] {'x': None}

Answer: None {'x': None}. setdefault leaves an existing value, including None, unchanged.

What does this program print? d = {"a": 1} answer = d.update({"a": 2}) print(answer, d["a"])

  • 2 2
  • None 2
  • None 1
  • {'a': 2} 2

Answer: None 2. update changes the dictionary in place and returns None.

What does this program print? d = {"a": 1} view = d.keys() saved = list(d) d["b"] = 2 print(list(view), saved)

  • ['a'] ['a']
  • ['a', 'b'] ['a', 'b']
  • ['a'] ['a', 'b']
  • ['a', 'b'] ['a']

Answer: ['a', 'b'] ['a']. The keys view is live, but the saved list is a snapshot.

What does this program print? d = dict.fromkeys(["a", "b"], []) d["a"].append(7) print(d["b"])

  • []
  • None
  • [7]
  • KeyError

Answer: [7]. Both keys refer to the same list supplied as the default.

How can you delete selected keys while iterating a stable set of the original keys?

  • Iterate list(d), delete from d
  • Iterate d, delete from d
  • Iterate d.keys(), delete from d
  • Iterate d.items(), delete from d

Answer: Iterate list(d), delete from d. A separate list preserves the iteration input while the dictionary changes.

What does this program print? a = {"x": 1, "y": 2} b = {"x": 9} c = a | b print(c["x"], a["x"])

  • 1 1
  • 9 9
  • 1 9
  • 9 1

Answer: 9 1. The right operand wins in a new mapping; a remains unchanged.

What does this program print? d = {"a": 1, "b": 2} d["a"] = 9 print(d.popitem())

  • ('a', 9)
  • ('b', 2)
  • ('a', 1)
  • ('b', 9)

Answer: ('b', 2). Updating a does not move its insertion position; b remains the last inserted key.

Continue this course

Related lessons