source: kdnuggets: python dictionary tips and tricks you should always remember
level: technical
using .get() instead of square brackets prevents keyerror crashes by returning a default value when a key is missing. for example, config.get("timeout", 30) safely returns 30 if "timeout" is not in the dictionary. this is useful for optional configs or api responses where missing keys are expected. however, if a missing key indicates a bug, square brackets are better because they raise an error immediately.
defaultdict from the collections module simplifies grouping and counting. when counting word frequencies, defaultdict(int) automatically initializes missing keys to zero, removing the need for manual checks. merging dictionaries is now straightforward with the | operator, where defaults | overrides combines two dicts and gives priority to the right-hand dict in case of key overlap. the |= operator updates a dict in place.
dictionary unpacking with ** passes dict items as keyword arguments to functions, matching keys to parameter names and falling back to defaults for missing keys. the walrus operator (:=) reduces repeated lookups in nested dicts by assigning and checking a value in one step. typeddict adds type hints for dictionary structures, enabling static checkers like mypy to catch type mismatches early. finally, iterating with .items() is cleaner and avoids extra lookups compared to looping over keys and indexing.
why it matters: these patterns reduce bugs, improve readability, and make dictionary-heavy code more maintainable in data pipelines and ml workflows.
source: kdnuggets: python dictionary tips and tricks you should always remember