Mukund Gandlur
Mukund Gandlur

Reputation: 869

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.

Upvotes: 16

Views: 19191

Answers (4)

Muhammad Tahir
Muhammad Tahir

Reputation: 5184

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

Upvotes: 19

simleo
simleo

Reputation: 2965

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

Upvotes: 4

Pedru
Pedru

Reputation: 1450

Exceptions in Python are not very expensive.

Plus, if you consider that most of the time the key you are looking for (the count) is there, then it is totally fine.

d = {}
while True:
    try:
        d['count'] += 1
    except KeyError:
        d['count'] = 1  # happens only once

Upvotes: 0

Serge Ballesta
Serge Ballesta

Reputation: 148890

collections.defaultdict could help to build a pythonic code:

count = collections.defaultdict(int) # => default value is 0
...
count[event] += 1 # will end to 1 on first hit and will increment later

Upvotes: 2

Related Questions