Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to handle a keyerror in a dict

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.

like image 822
Mukund Gandlur Avatar asked Apr 13 '16 12:04

Mukund Gandlur


2 Answers

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
like image 54
Muhammad Tahir Avatar answered Oct 19 '22 18:10

Muhammad Tahir


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
like image 25
simleo Avatar answered Oct 19 '22 19:10

simleo