18

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.

4
  • 3
    what about collections.Counter? Commented Apr 13, 2016 at 12:09
  • Ok, I will try that. Is there something like a get("<key>","<default value>") Commented Apr 13, 2016 at 12:14
  • 2
    @MukundGandlur Try defaultdict Commented Apr 13, 2016 at 12:14
  • 3
    yes there is exactly that get you're talking about Commented Apr 13, 2016 at 12:15

4 Answers 4

21

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
Sign up to request clarification or add additional context in comments.

2 Comments

.get would be fine, setdefault for mutable in-place values
.get is exactly what I was looking for. It's nice not to have try except everywhere in the code.
4

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

Comments

2

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

1 Comment

No Counter? ... that would be more ... Pythonic.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.