简体   繁体   中英

Is checking for the existence of a key in a dictionary better than catching a KeyError in Python?

I have a bit of experience in Python but I'm taking the Udacity computer science course to fill in the gaps of what I've learned and to supplement what I already know. The course went over a hashtable lookup function that returns None for the value of a key if the key isn't in the hashtable. Python's dictionary type throws a KeyError when the key doesn't exist, so the course says to use key in mydict before getting its value.

What I'm wondering is if it's better to do:

mydefaultval = 75
key = ..
mydict = ..
if key in mydict:
    val = mydict[key]
else:
    val = mydefaultval

.. or

mydefaultval = 75
key = ..
mydict = ..
try:
    val = mydict[key]
except KeyError:
    val = mydefaultval

I would imagine that for Python to check if the key exists, it has to find it in the dictionary. If I then grab the value at that key, it has to do the same thing twice. Am I correct for thinking this, or will Python do something else?

The best thing is to use dict.get:

val = my_dict.get(key, mydefaultval)

If there weren't an awesome method like this, I'd recommend using the exception. Python culture is that exceptions are not forbidden, and often the explicit check will actually be catching exceptions anyway.

If the default is going to be the same value every time you use a particular dict, another option is to use collections.defaultdict . It's more verbose to declare the dict than the dict.get() solution, but much terser in usage:

>>> from collections import defaultdict
>>> mydict = defaultdict( lambda: 75 )
>>> mydict[3]
75

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM