defaultdict: a hidden gem of Python standard library

Often you need to store data (counters, sums, lists, etc.) about some entities. A regular Python dictionary will suffice with one caveat: before adding information regarding a particular entity you need to check if the corresponding key exists in the dictionary, otherwise you will get a KeyError. Do not know about you, but I have written similar code many times: dct = {} if key not in dct: dct['key'] = 0 dct['key'] += 1 A better way While it is perfectly workable, it does not add to readability....

2021-10-25 · 2 min