Python Tutorial
Python Add Dictionary Items
Adding an item is assigning to a new key. update() can add several keys.
Adding Items
A new key creates a new item.
thisdict = {"brand": "Ford", "model": "Mustang", "year": 1964}
thisdict["color"] = "red"
thisdict.update({"owner": "Luna"})
print(thisdict)📘 Real-World Deep Dive
Adding to a dict has subtle variants — <code>__setitem__</code>, update, setdefault, merge <code>|</code>. The right choice depends on whether you want to preserve, overwrite, or collapse duplicates.
Real-Life Scenario
Build a call-frequency counter from a log line-by-line; combine a manual loop with final merge to read two days worth of files.
Real-Life Example
import csv, io
from collections import Counter
day1 = "api,/users,200\napi,/login,200\ndb,SELECT,401\napi,/users,200\n"
day2 = "api,/users,500\ndb,SELECT,401\napi,/users,200\napi,/login,200\n"
def parse(line: str):
# route,endpoint,code
route, ep, code = line.strip().split(",", 2)
return (route, ep), int(code)
c: Counter = Counter()
for line in (day1 + day2).splitlines():
if not line: continue
key, _ = parse(line)
c[key] += 1
print("frequencies:")
for key, n in c.most_common():
print(f" {key}: {n}")
Expected Output
frequencies:
('api', '/users'): 4
('api', '/login'): 3
('db', 'SELECT'): 2Common mistakes
- Mutating
d[k]works on existing keys; used.setdefault(k, default)only if you specifically need lazy initialisation. d.update(other)silently overwrites; carry the old value first if you need to log changes.d |= otherrequires Python 3.9+; used.update(other)on older interpreters.
🚀 Performance & Best Practices
d[k] = vis O(1) on average; rehashing happens at load-factor boundaries.- Bulk insertion from a sequence of pairs is faster with a single
updatethan per-key writes. - For huge dicts, use
array.arrayfor keys plus a parallel value array.
🧪 Try It Yourself
- Build a
coalesce(d1, d2, prefer=last)helper that accepts an override-fail mode. - Add a decorator that records every write to
dfor replay. - Switch the example to use
collections.Counterdirectly.