31
MyDict = {'key1':'value1', 'key2':'value2'}

I can do this few ways:

if 'key1' in MyDict:
       var1 = MyDict['key1']

or

if MyDict.has_key('key1'):
       var1 = MyDict['key1']

or

if MyDict['key1']:
    var1=MyDict['key1']

or

try: 
   var1=MyDict['key1]
except KeyError, e:
   pass

or I tried something like this but it does NOT WORK like this in python

if v=MyDict.get('key1'):
       var1=v

And we cold probably figure out lot more working ways to do that. Which one is most efficient in terms of computing speed?

6
  • 7
    dict.has_key() has been deprecated, and is gone in Python 3. Do not use it.
    – Martijn Pieters
    Mar 4, 2015 at 16:03
  • Your examples are not all the same. The first two check if the dictionary has a specific key while the third tests the boolean value of that key (and assumes it is there).
    – user2555451
    Mar 4, 2015 at 16:09
  • @iCodez but in this case empty value will resolve as False and non empty as True - this also works, assuming I dont use 0, False or None in my values. Correct?
    – Lord_JABA
    Mar 4, 2015 at 16:15
  • 2
    If 'key1' is not an item in the dictionary, the first two examples will work fine while the third will raise a KeyError exception.
    – user2555451
    Mar 4, 2015 at 16:16
  • How often is the key going to be missing? Yes, that matters.
    – Martijn Pieters
    Mar 4, 2015 at 16:24

3 Answers 3

61

A little benchmark for you (ipython):

In [1]: def test_1(d, k):
   ...:     if k in d:
   ...:         var1 = d[k]
   ...:         

In [2]: def test_2(d, k):
   ...:     if d.has_key(k):
   ...:         var1 = d[k]
   ...:         

In [3]: def test_3(d, k):
   ...:     try:
   ...:         var1 = d[k]
   ...:     except KeyError as e:
   ...:         pass
   ...:     

In [4]: def test_4(d, k):
   ...:     if d.get(k):
   ...:         var1 = d[k]
   ...:         

In [5]: my_dict = {'key{}'.format(i): 'value{}'.format(i) for i in range(1000)}

In [6]: key_valid = "key5"

In [7]: key_non_valid = "key"

In [8]: %timeit test_1(my_dict, key_valid)
10000000 loops, best of 3: 172 ns per loop

In [9]: %timeit test_1(my_dict, key_non_valid)
10000000 loops, best of 3: 132 ns per loop

In [10]: %timeit test_2(my_dict, key_valid)
1000000 loops, best of 3: 211 ns per loop

In [11]: %timeit test_2(my_dict, key_non_valid)
10000000 loops, best of 3: 171 ns per loop

In [12]: %timeit test_3(my_dict, key_valid)
10000000 loops, best of 3: 151 ns per loop

In [13]: %timeit test_3(my_dict, key_non_valid)
1000000 loops, best of 3: 1.07 µs per loop

In [14]: %timeit test_4(my_dict, key_valid)
1000000 loops, best of 3: 246 ns per loop

In [15]: %timeit test_4(my_dict, key_non_valid)
10000000 loops, best of 3: 189 ns per loop

Conclusion: construction key in dict is generally fastest, outperformed only by try except in case of valid key, because it doesn't perform if operation.

(note however try except is significantly slower for invalid keys: therefore, since the whole point is you don't know if key is valid, then given an unknown probability of valid vs. invalid, stick with key in dict).

4
  • 2
    If you can ensure values are truthy. Would var1 = d.get(k, None); if var1: ... be faster?
    – AnnanFay
    Feb 7, 2017 at 23:10
  • 2
    I would want to point that try: except: has the worst performance if the key is not valid. 1.07 µs > 132 ns. I don't understand the "outperformed" of the answer when the difference is more than 800ns when the key doesn't exist and 20ns in favour of try/except when the key exists.
    – Bechma
    Jul 25, 2018 at 7:41
  • 2
    @Bechma I just tested this with 60k keys and try except took 1 second whereas k in d took 61 seconds. Jun 11, 2019 at 22:34
  • 2
    remember, .has_key is not in python3.8 or python3.9 (not %100 about older python3's)
    – wamster
    Feb 17, 2021 at 6:50
4

Assuming you dont want var1 to be defined only if MyDict["key1"] is set, the obvious solution is var1 = MyDict.get("key1", default=some_sentinel_or_default_value).

wrt/ performances, it mostly depends on whether you expect "key1" to be in your dict most of the times or not. If the first, a try/except block might be faster, else it will be slower (try/except blocks are cheap to setup but costly when there's an actual exception).

If you really worry that much about performances, I suggest you test the various options on real-life data using the timeit module.

2
  • Not what I want in this case. I want to touch var1 only if key is present (var1 may be set earlier) Your method would overwrite var1 with default every time the key does not exist
    – Lord_JABA
    Mar 4, 2015 at 16:20
  • 1
    Use var1 = MyDict.get("key1", var1) then. Mar 4, 2015 at 16:28
2

This one of your methods is very fast:

if 'key1' in MyDict:
       var1 = MyDict['key1']

Assuming certain conditions on the items in your dictionary and the hashing, this should be on average O[1]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.