Dictionary methods help read, update, loop through, and safely manage key-value data.
Use the method that matches your missing-key behavior: fail loudly, return a default, create a default, or remove a key.
Clear dictionary code makes data records, lookup tables, counters, and configuration objects easier to maintain.
Use direct indexing when a missing key should be an error. Use get() when missing data has a safe fallback.
Membership testing separates a missing key from a key whose value is None: use key in mapping when that distinction matters. get does not insert the fallback. By contrast, setdefault returns an existing value or stores the supplied default, so it is a mutating operation even when it appears in an expression.
user = {"name": "Maya", "role": "admin"}
theme = user.get("theme", "light")
print(theme)
light
theme is missing, so get() returns the fallback value instead of raising KeyError.
update() merges new keys and values into a dictionary.
The | operator creates a new merged dictionary, while update and |= mutate the left dictionary. In every form, the rightmost value wins for a duplicate key. A shallow merge replaces a nested dictionary as one value; it does not recursively merge nested settings.
settings = {"theme": "light", "font_size": 14}
changes = {"theme": "dark", "sidebar": True}
settings.update(changes)
print(settings)
{'theme': 'dark', 'font_size': 14, 'sidebar': True}
theme was replaced, and sidebar was added.
items(), keys(), and values() let you loop through dictionary content.
keys, values, and items return dynamic view objects rather than frozen lists. A view reflects later dictionary changes and supports efficient membership tests. Do not change the dictionary size while iterating over one of its views; iterate over list(mapping.items()) when removal during the loop is intentional.
setdefault(), get(), defaultdict, and Counter are common counting tools.
A get-based counter is explicit and dependency-free. defaultdict is useful when every missing key should construct the same kind of mutable bucket. Counter adds frequency operations such as most_common and arithmetic between counts. Choose based on the output operations, not only the shortest initialization.
del mapping[key] removes a required key and raises KeyError when it is absent. pop removes a key and returns its value; a second argument supplies a fallback for an absent key. popitem removes and returns the most recently inserted pair, which is useful for destructive stack-like processing but should not replace clear queue logic.
clear removes every entry from the same dictionary object. Existing references observe the now-empty mapping. Rebinding a variable to {} creates a different object and leaves other references unchanged. This difference matters when a dictionary is shared through a cache, dependency, or caller-owned argument.
session = {"user_id": 42, "draft": "hello", "debug": True}
debug_enabled = session.pop("debug", False)
draft = session.pop("draft")
print(debug_enabled)
print(draft)
print(session)
True
hello
{'user_id': 42}
debug has an expected fallback, while draft is required and would raise KeyError if the session contract were broken.
copy returns a shallow dictionary. The outer mapping is independent, but nested lists and dictionaries are still shared. Use copy.deepcopy only when an independent object graph is required and the contained types support deep copying. In many applications, constructing a new validated value object is clearer than cloning arbitrary state.
For nested access, chained get calls can become ambiguous and can fail when an intermediate value is None or the wrong type. Validate the shape at the boundary, then use direct indexing for required fields. A helper that follows a known path is appropriate when the missing-value policy is consistent and documented.
original = {"name": "Maya", "tags": ["python"]}
copied = original.copy()
copied["name"] = "Ravi"
copied["tags"].append("data")
print(original["name"])
print(original["tags"])
Maya
['python', 'data']
The top-level name entry is independent, but both dictionaries still refer to the same nested tags list.
Choose the method from the missing-key and mutation contract. Required read: indexing. Optional read without insertion: get. Optional read with insertion: setdefault. Required removal: del or pop without a fallback. Optional removal: pop with a fallback. Pair iteration: items. Non-mutating merge: |. In-place merge: update or |=.
The most maintainable call is the one that exposes an unexpected state. A fallback is not automatically safer: silently substituting zero for a missing invoice amount can hide corrupt input. Reserve defaults for cases where the domain genuinely defines one, and test both the present and absent path.
Try this next
0 of 3 completed
No. get() can hide missing required data. Use direct indexing when a missing key should fail.
It returns the existing value for a key, or stores and returns a default value if the key is missing.
Modern Python dictionaries preserve insertion order, but choose dictionaries for key lookup first, not for sequence behavior.
Explore 500+ free tutorials across 20+ languages and frameworks.