defaultdict creates on read¶
Level: 201 · for Python programmers
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The bullets below are the questions the finished page has to answer.
One line: A defaultdict calls its factory on every missing key you read, so if d[k]: inserts k, len(d) grows during a loop that only looked, and d.get(k) does not trigger it at all — which is __missing__, and it makes Counter's zero and dict.setdefault's explicit spelling the two things to compare it with.
What the finished page has to answer¶
d[k]againstd.get(k)againstk in don a missing key, measured withlen(d)after each.__missing__as the hook, and adictsubclass with its own.Counter[k]returns0without inserting, which is the opposite decision made by the same module.dict.setdefault(k, [])as the one-line spelling, and why its default is evaluated on every call wheredefaultdict(list)calls the factory only on a miss.- The grouping idiom,
defaultdict(list)fed by a loop, againstgroupby, and the counting idiom againstCounter. dict.fromkeys(keys, [])handing every key the one list, which Assignment does not copy measures.- The neighbours:
OrderedDictequality is order-sensitive wheredictequality is not, andpopitem()is last-in first-out.
See also¶
- Assignment does not copy and
groupbygroups runs, not keys collections.defaultdict↗ in the library reference, andobject.__missing__↗- The
HashMap↗ in the Rust library, whereentry(k).or_insert(…)is the explicit spelling of the same idea