Should I use 'has_key()' or 'in' on Python dicts?
我想知道做什么更好:
1 2 3 | d = {'a': 1, 'b': 2} 'a' in d True |
或:
1 2 3 | d = {'a': 1, 'b': 2} d.has_key('a') True |
语言是
事实上
1 2 3 4 | $ python -mtimeit -s'd=dict.fromkeys(range(99))' '12 in d' 10000000 loops, best of 3: 0.0983 usec per loop $ python -mtimeit -s'd=dict.fromkeys(range(99))' 'd.has_key(12)' 1000000 loops, best of 3: 0.21 usec per loop |
而下面的观测是不总是真的,你会注意到,通常,在Python中,更快的解决方案是更多的优雅与语言;这就是为什么
根据Python文档:
has_key() is deprecated in favor of
key in d .
使用
有一个例子是在
如果你使用
我是一个平凡的固定:
1 2 | def __contains__(self, x): return self.has_key(x) |
解决方案_ key()是一dict.has使用过时的,在3 -崇高的文本编辑器
在这里我有两例年龄"命名的大学词典
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | ages = {} # Add a couple of names to the dictionary ages['Sue'] = 23 ages['Peter'] = 19 ages['Andrew'] = 78 ages['Karren'] = 45 # use of 'in' in if condition instead of function_name.has_key(key-name). if 'Sue' in ages: print"Sue is in the dictionary. She is", ages['Sue'],"years old" else: print"Sue is not in the dictionary" |
扩大在Alex Martelli Parkin的性能测试与亚当的评论……
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | $ python3.5 -mtimeit -s'd=dict.fromkeys(range( 99))' 'd.has_key(12)' Traceback (most recent call last): File"/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/timeit.py", line 301, in main x = t.timeit(number) File"/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/timeit.py", line 178, in timeit timing = self.inner(it, self.timer) File"<timeit-src>", line 6, in inner d.has_key(12) AttributeError: 'dict' object has no attribute 'has_key' $ python2.7 -mtimeit -s'd=dict.fromkeys(range( 99))' 'd.has_key(12)' 10000000 loops, best of 3: 0.0872 usec per loop $ python2.7 -mtimeit -s'd=dict.fromkeys(range(1999))' 'd.has_key(12)' 10000000 loops, best of 3: 0.0858 usec per loop $ python3.5 -mtimeit -s'd=dict.fromkeys(range( 99))' '12 in d' 10000000 loops, best of 3: 0.031 usec per loop $ python3.5 -mtimeit -s'd=dict.fromkeys(range(1999))' '12 in d' 10000000 loops, best of 3: 0.033 usec per loop $ python3.5 -mtimeit -s'd=dict.fromkeys(range( 99))' '12 in d.keys()' 10000000 loops, best of 3: 0.115 usec per loop $ python3.5 -mtimeit -s'd=dict.fromkeys(range(1999))' '12 in d.keys()' 10000000 loops, best of 3: 0.117 usec per loop |
Python Python 3.x
如果你有像这样的东西
1 | t.has_key(ew) |
改变它的运行在下面的Python 3.x及以上
1 2 | key = ew if key not in t |