Python 检查字典键是否存在并在存在时处理其值的最有效方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28859095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:50:34  来源:igfitidea点击:

Most efficient method to check if dictionary key exists and process its value if it does

pythonperformancedictionary

提问by Lord_JABA

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']
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

或者我尝试过这样的事情,但它在 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?

我们很可能会想出更多可行的方法来做到这一点。哪一种在计算速度方面最有效?

采纳答案by pavel_form

A little benchmark for you (ipython):

给你的一个小基准(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 dictis generally fastest, outperformed only by try exceptin case of valid key, because it doesn't perform ifoperation.

结论:构造key in dict通常是最快的,只有try except在有效密钥的情况下才表现得更好,因为它不执行if操作。

回答by StackG

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]

假设你的字典中的项目和散列有一定的条件,这平均应该是 O[1​​]

回答by bruno desthuilliers

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

假设你希望var1被仅定义MyDict["key1"]设置,显而易见的解决方案是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).

wrt/表演,这主要取决于您是否希望“key1”在大多数情况下都在您的字典中。如果是第一个,try/except 块可能会更快,否则它会更慢(try/except 块设置起来很便宜,但在出现实际异常时成本很高)。

If you really worry that much about performances, I suggest you test the various options on real-life datausing the timeitmodule.

如果您真的非常担心性能,我建议您使用该模块测试真实数据的各种选项timeit