How to initially increase the value of a dictionary element?

When working with Python 3 dictionaries, I have to do something like this:

d=dict() if 'k' in d: d['k']+=1 else: d['k']=0 

I seem to remember that there was a native way to do this, but looked through the documentation and could not find it. Do you know what it is?

+5
source share
2 answers

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}) 
+12
source

Note that you can always remove the clutter from if stamemt using it in the expression:

 d['k'] = d['k'] + 1 if 'k' in d else 0 
0
source

All Articles