I would like to know the best way to handle a keyerror, when I try to get a value from a dict.
I need this because my dict holds the counts of some events. And whenever an event occurs I take the count from the dict and increment it and put it back.
I found some solutions online, but they were for some other languages. Any help is appreciated.
I am handling the keyerror exception now. Would like to know the best approach to handle a keyerror in a dictionary.
Note: This is not about counting items in a list but about handling exception when retrieving a value(that does not exist) from a dict.
You can use dict.get
if you want to use dict
mydict[key] = mydict.get(key, 0) + 1
Or you can handle KeyError
try:
mydict[key] += 1
except KeyError:
mydict[key] = 1
Or you can use defaultdict
from collections import defaultdict
mydict = defaultdict(int)
mydict[key] += 1
The most appropriate data structure for what you want to do is collections.Counter
, where missing keys have an implicit value of 0
:
from collections import Counter
events = Counter()
for e in "foo", "bar", "foo", "tar":
events[e] += 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With