Dictionary methods
- Version
- 3.14
- Review
- Draft
Summary#
Dictionary methods read, insert, remove and combine key and value pairs. get reads with a fallback, setdefault inserts a missing key, and pop removes a key and returns its value.
Syntax#
mapping.get(key, default)
mapping.setdefault(key, default)
mapping.pop(key, default)
mapping.update(other)
for key, value in mapping.items():
pass
merged = mapping | other
Example#
stock = {"apple": 3, "pear": 0}
print(stock.get("apple"), stock.get("kiwi"), stock.get("kiwi", 0))
print(stock.setdefault("kiwi", 5), stock.setdefault("apple", 99))
print(stock.pop("pear"), stock.pop("fig", None))
merged = stock | {"apple": 10, "fig": 1}
for name, count in merged.items():
print(name, count)
print(stock)
Expected output#
3 None 0
5 3
0 None
apple 10
kiwi 5
fig 1
{'apple': 3, 'kiwi': 5}
Common mistakes#
mapping.get(key) or fallback also replaces a stored 0, empty string or False. Pass the fallback as the second argument when only a missing key should use it. Adding or deleting keys while iterating a view may raise RuntimeError or skip entries. Iterate over list(mapping) to snapshot the keys first. For the built-in dict merge with |, use dictionaries on both sides. The right side wins on duplicate keys, and the inputs stay unchanged.
Version applicability#
The methods shown work on all Python 3 releases, where items() returns a view. Insertion order has been guaranteed since Python 3.7. The merge operator | and the update operator |= require Python 3.9 or later, so the example starts at 3.9.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0