Question presented to candidate: "Walk me through the everyday dictionary toolkit in Python. How do you read a key that might be missing, group items into lists, loop over keys and values, and merge two dictionaries โ and which of those have traps?"
What a strong answer should cover:
d[key]raisesKeyError;d.get(key, default)returns a default instead, andd.get(k) or xis wrong when the stored value is falsy.intests keys, not values.setdefault(key, default)returns the value and inserts the default first if the key is missing โ the classic grouping idiom โ but the default expression is evaluated on every call;collections.defaultdictcalls its factory only for missing keys.keys(),values()anditems()return live views;items()is how you loop over key/value pairs; key views support set operations; deleting while iterating raisesRuntimeError.- Merging:
{**a, **b},a | b(Python 3.9, PEP 584),a |= bandupdate()โ the right-hand side wins, merging is shallow, and|needs a mapping on the right while|=/updatealso take an iterable of key/value pairs. - Dicts keep insertion order (a language guarantee since 3.7); overwriting a key keeps its position,
popitemremoves the last item,dict.fromkeysshares one value object.
Code / implementation expected: Yes โ a word-grouping or counting snippet, and a config merge with defaults overridden by user values.