alessandro308
alessandro308

Reputation: 2162

Using Python dictionary, it is better to check the key presence or catch the exception?

I've written a code that uses largely the Python dictionary for incrementing some counters (the number of counters is not fixed)

The common pattern is:

if not key in dictionary1:
    dictionary1[key] = init()
dictionary[key]["last_value"] += current_value

In order to speed up my code execution, it is better to write a try-catch clause instead of a conditional statement?

For instance,

try:
  dictionary[key]["last_value"] += current_value
except KeyError:
  dictionary[key] = init()
  dictionary[key]["last_value"] += current_value

Upvotes: 1

Views: 69

Answers (3)

Tobias Brösamle
Tobias Brösamle

Reputation: 598

The more pythonic way is: ask for foregiveness, not for permission. But as you can see, you would have to double code, which is also bad.

Luckyly, there's another solution:

dictionary.setdefault(key, init())["value"] += current_value

So, if dictionary does not contain key, setdefault will create it and assign the result of init to it. Then, you can assign your own value.

NOTE: As stated in the comments by L3viatan, this is not a good choice if init() is doing anything else than returning a value like manipulating a global variable or doing some very time intensive work, because init() will be called every time this line is executed. The returned value will just be ignored.

Upvotes: 1

Vignesh Bayari R.
Vignesh Bayari R.

Reputation: 663

Looks like dictionary.get(key, default) can be used here. As for the try-catch, use it for legitimate exception handling.

You may have to do it this way:

if dictionary.get(key, None) is None:
    dictionary[key] = init()

dictionary[key]["last_value"] += current_value

Upvotes: 1

lxop
lxop

Reputation: 8595

Use a defaultdict:

from collections import defaultdict

dictionary = defaultdict(init)
dictionary[key]["last_value"] += current_value

If the key is not in the dictionary when it is looked up, it will be added, with the value given by init().

Upvotes: 4

Related Questions