Python Essentials for AI Engineer

Course Content

Python Essentials for AI Engineer

6 sections · 48 lessons

What are dictionary methods?


What you need to know

MethodWhat it doesReturns
d.keys() / d.values() / d.items()live views of keys, values, (key, value) pairsview objects
d.get(k, default)value, or default if missing (no insert)value
d.setdefault(k, default)value; if missing, inserts default firstvalue
d.update(other)merges other in; its keys winNone
d.pop(k, default)removes k and returns its valuevalue
d.popitem()removes the last inserted pair(key, value)
d.copy()shallow copynew dict
d.clear()empties itNone
dict.fromkeys(keys, v)new dict with every key set to vnew dict

Views are live

Python
cfg = {"model": "chat-small"}keys = cfg.keys()cfg["temperature"] = 0.2print(keys)                 # dict_keys(['model', 'temperature'])  -> reflects the changeprint(list(keys)[0])        # model  -> views can't be indexed; convert first

A 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
scores = {"d1": 0.9, "d2": 0.1, "d3": 0.4}try:    for k in scores:        if scores[k] < 0.5:            del scores[k]except RuntimeError as e:    print(e)                # dictionary changed size during iterationscores = {"d1": 0.9, "d2": 0.1, "d3": 0.4}scores = {k: v for k, v in scores.items() if v >= 0.5}   # build a new dict insteadprint(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
results = [    ("refund", True), ("kyc", False), ("refund", False),    ("upi", True), ("kyc", False), ("refund", True),]failures = {}for category, passed in results:    bucket = failures.setdefault(category, [0, 0])   # [passed, failed]    bucket[0 if passed else 1] += 1for category, (ok, bad) in failures.items():    print(f"{category:<7} pass={ok} fail={bad}")# refund  pass=2 fail=1# kyc     pass=0 fail=2# upi     pass=1 fail=0defaults = {"model": "chat-small", "temperature": 0.2, "max_tokens": 512}run = defaults | {"temperature": 0.0}      # new dict; defaults untouchedprint(run["temperature"], defaults["temperature"])   # 0.0 0.2

setdefault 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.
  • "setdefault vs defaultdict?" — Same idea. defaultdict(list) sets a default factory once for the whole dict; setdefault is per call and evaluates its default argument every time, even when the key exists.
  • "update() vs |?" — update changes the dict in place; | returns a new dict. |= is the in-place form.