检查字典密钥是否存在并处理其值的最有效方法 [英] Most efficient method to check if dictionary key exists and process its value if it does
本文介绍了检查字典密钥是否存在并处理其值的最有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
MyDict = {'key1':'value1', 'key2':'value2'}
我可以通过以下几种方法:
I can do this few ways:
if 'key1' in MyDict:
var1 = MyDict['key1']
或
if MyDict.has_key('key1'):
var1 = MyDict['key1']
或
or
if MyDict['key1']:
var1=MyDict['key1']
或
or
try:
var1=MyDict['key1]
except KeyError, e:
pass
或者我尝试过这样的东西,但它在python中不会这样工作如果v = MyDict.get('key1'):
var1 = v
$
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?
推荐答案
一个小的基准(ipython):
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
结论:dict中的构造键在
中通常最快,只有尝试除
之外的有效键,因为它不执行如果
操作。
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.
这篇关于检查字典密钥是否存在并处理其值的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文