This is a use case for collections.defaultdict , just using an int , which can be used for the factory by default.
>>> from collections import defaultdict >>> d = defaultdict(int) >>> d defaultdict(<class 'int'>, {}) >>> d['k'] +=1 >>> d defaultdict(<class 'int'>, {'k': 1})
A defaultdict configured to create items whenever a missing key is searched. You provide it with a callable (here int() ), which it uses to get the default value when a search with __getitem__ is passed in with a key that does not exist. This callee is stored in an instance attribute called default_factory .
If you did not specify default_factory , you will receive a KeyError as usual for missing keys.
Then suppose you need a different default value, possibly 1 instead of 0. You just need to pass the caller, which gives the desired initial value, in this case itβs very trivial
>>> d = defaultdict(lambda: 1)
This, obviously, can also be any regular named function.
However, it is worth noting that if in your case you are trying to just use a dictionary to store a counter of certain values, collections.Counter more suitable for work.
>>> from collections import Counter >>> Counter('kangaroo') Counter({'a': 2, 'o': 2, 'n': 1, 'r': 1, 'k': 1, 'g': 1})
source share