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
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments