Course Content
Python Essentials for AI Engineer
6 sections · 48 lessons
What are dictionary methods?
What you need to know
| Method | What it does | Returns |
|---|---|---|
d.keys() / d.values() / d.items() | live views of keys, values, (key, value) pairs | view objects |
d.get(k, default) | value, or default if missing (no insert) | value |
d.setdefault(k, default) | value; if missing, inserts default first | value |
d.update(other) | merges other in; its keys win | None |
d.pop(k, default) | removes k and returns its value | value |
d.popitem() | removes the last inserted pair | (key, value) |
d.copy() | shallow copy | new dict |
d.clear() | empties it | None |
dict.fromkeys(keys, v) | new dict with every key set to v | new dict |
Views are live
Python
1cfg = {"model": "chat-small"}2keys = cfg.keys()3cfg["temperature"] = 0.24print(keys) # dict_keys(['model', 'temperature']) -> reflects the change5print(list(keys)[0]) # model -> views can't be indexed; convert firstA view is a window onto the dict, not a copy. It is cheap to create and always up to date. keys() and items() views also support set operations, such as a.keys() & b.keys() for the keys two configs share.
Don't change size while looping
Python
1scores = {"d1": 0.9, "d2": 0.1, "d3": 0.4}2try:3 for k in scores:4 if scores[k] < 0.5:5 del scores[k]6except RuntimeError as e:7 print(e) # dictionary changed size during iteration89scores = {"d1": 0.9, "d2": 0.1, "d3": 0.4}10scores = {k: v for k, v in scores.items() if v >= 0.5} # build a new dict instead11print(scores) # {'d1': 0.9}Loop over list(scores) if you must delete in place.
A real-life example
You evaluate a support bot on 6 test questions and want failures grouped by category, plus a run config built from defaults and per-run overrides:
Python
1results = [2 ("refund", True), ("kyc", False), ("refund", False),3 ("upi", True), ("kyc", False), ("refund", True),4]5failures = {}6for category, passed in results:7 bucket = failures.setdefault(category, [0, 0]) # [passed, failed]8 bucket[0 if passed else 1] += 1910for category, (ok, bad) in failures.items():11 print(f"{category:<7} pass={ok} fail={bad}")12# refund pass=2 fail=113# kyc pass=0 fail=214# upi pass=1 fail=01516defaults = {"model": "chat-small", "temperature": 0.2, "max_tokens": 512}17run = defaults | {"temperature": 0.0} # new dict; defaults untouched18print(run["temperature"], defaults["temperature"]) # 0.0 0.2setdefault removes the "if key not in dict, create it" boilerplate. items() gives key and value in one step, without a second lookup. The | operator (Python 3.9+) merges into a new dict, so the shared defaults are never modified by one run.
Follow-up questions to expect
- "What is a dictionary view?" — A live, read-only window onto a dict's keys, values or items. It updates as the dict changes and is not a list.
- "
setdefaultvsdefaultdict?" — Same idea.defaultdict(list)sets a default factory once for the whole dict;setdefaultis per call and evaluates its default argument every time, even when the key exists. - "
update()vs|?" —updatechanges the dict in place;|returns a new dict.|=is the in-place form.