Python Tutorial
Python Change Dictionary Items
Change a value by referring to its key. update() can change several items at once.
Change Values
Assign to a key that already exists.
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
thisdict["year"] = 2018
thisdict.update({"year": 2020})
print(thisdict)📘 Real-World Deep Dive
Dict mutation has more variants than list mutation (<code>d[k] = v</code>, <code>d.update</code>, <code>d.setdefault</code>, comprehension). Picking the right one keeps logs intact and avoids stale references.
Real-Life Scenario
Update pricing rules: merge a small change-set into a base pricing map, then verify which keys changed.
Real-Life Example
from copy import deepcopy
BASE = {"starter": 0, "pro": 19, "enterprise": 99}
PATCH = {"pro": 25, "team": 39, "enterprise": 89}
patched = deepcopy(BASE)
patched.update(PATCH) # later wins; new keys appear
changed_keys = sorted(set(BASE) ^ set(patched))
print("base :", BASE)
print("patched:", patched)
print("toggled:", changed_keys)
# Conditional change with setdefault
def ensure_path(d, k, path):
d.setdefault(k, {}).setdefault("path", path)
od = {}
ensure_path(od, "user", "/users")
ensure_path(od, "user", "/users")
ensure_path(od, "post", "/posts")
print("od:", od)Expected Output
base : {'starter': 0, 'pro': 19, 'enterprise': 99}
patched: {'starter': 0, 'pro': 25, 'enterprise': 89, 'team': 39}
toggled: ['enterprise', 'team']
od: {'user': {'path': '/users'}, 'post': {'path': '/posts'}}Common mistakes
- Mutating a dict copy still mutates the original if values are mutable objects.
setdefault(...)evaluates the value expression each call — side-effects in that expression are unexpected.- Tuple keys (including
(namespace, key)) work but built-in tuples can't include lists.
🚀 Performance & Best Practices
d.update(other)is one C-level loop — much faster than per-key assignment.- Use
d |= otherfor in-place merge since Python 3.9. - Avoid
d.popin tight loops; it rehashes.
🧪 Try It Yourself
- Write a
change_set(old, new)that returns{"add": [...], "remove": [...], "update": [...]}. - Replace the merge step with
d |= PATCHand benchmark. - Implement a
deep_updatethat recursively merges nested dicts.