我应该在Python dicts上使用'has_key()'或'in'吗?

时间:2009-08-24 16:30:16

标签: python dictionary

我想知道做什么更好:

d = {'a': 1, 'b': 2}
'a' in d
True

或:

d = {'a': 1, 'b': 2}
d.has_key('a')
True

9 个答案:

答案 0 :(得分:1144)

in肯定更像是pythonic。

事实上has_key() was removed in Python 3.x

答案 1 :(得分:244)

in赢得了胜利,不仅仅是优雅(并且不被弃用;-),还有性能,例如:

$ 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中,更快的解决方案更优雅和Pythonic;这就是为什么-mtimeit非常有用 - 它不是只是关于在这里和那里保存一百纳秒! - )

答案 2 :(得分:88)

根据python docs

  

has_key()已弃用赞成   key in d

答案 3 :(得分:39)

如果(且仅当)您的代码需要由早于2.3的Python版本(引入dict.has_key()时)运行,请使用key in dict

答案 4 :(得分:15)

has_key是一种字典方法,但in适用于任何集合,即使缺少__contains__in也会使用任何其他方法来迭代集合找出来。

答案 5 :(得分:14)

不推荐使用dict.has_key()的解决方案,使用'in' - sublime text editor 3

这里我举了一个名为'age'的字典的例子 -

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"

答案 6 :(得分:11)

利用亚当帕金的评论扩大Alex Martelli的表现测试......

$ 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

答案 7 :(得分:9)

Python 2.x支持has_key()

Python 2.3+和Python 3.x支持in

答案 8 :(得分:1)

如果你有类似的东西

Get-ChildItem

将其更改为以下内容,以便在Python 3.X及更高版本

上运行
Get-Item