has_key or in
来源:互联网 发布:倩女幽魂mac可以玩吗 编辑:程序博客网 时间:2024/06/08 19:35
'has_key()' or 'in'?
I wonder what is better to do:
d = {'a': 1, 'b': 2}'a' in dTrue
or:
d = {'a': 1, 'b': 2}d.has_key('a')True
11 Answers
in
is definitely more pythonic.
In fact has_key()
was removed in Python 3.x.
in
wins hands-down, not just in elegance (and not being deprecated;-) but also in performance, e.g.:
$ 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
While the following observation is not always true, you'll notice that usually, in Python, the faster solution is more elegant and Pythonic; that's why -mtimeit
is SO helpful -- it's not just about saving a hundred nanoseconds here and there!-)
has_key
appears to be O(1) too. – dan-gph Jan 6 '15 at 4:11According to python docs:
has_key()
is deprecated in favor ofkey in d
.
Use dict.has_key()
if (and only if) your code is required to be runnable by Python versions earlier than 2.3 (when key in dict
was introduced).
in
of course, duh" answers. – John Y Aug 3 '11 at 21:07There is one example where in
actually kills your performance.
If you use in
on a O(1) container that only implements __getitem__
and has_key()
but not __contains__
you will turn an O(1) search into an O(N) search (as in
falls back to a linear search via __getitem__
).
Fix is obviously trivial:
def __contains__(self, x): return self.has_key(x)
has_key
is a dictionary method, but in
will work on any collection, and even when __contains__
is missing, in
will use any other method to iterate the collection to find out.
- has_key or in
- 【Python基础】之has_key(key) or key in d
- Python从2.6版本后中将has_key换成in
- Python 判断是否在字典里用in还是has_key()
- python判断key是否在字典里用in还是用has_key()
- Python dict.has_key()方法
- Python 字典(Dictionary) has_key()方法
- In or Exists
- B. OR in Matrix
- PostgreSQL OR IN ANY
- B. OR in Matrix
- B. OR in Matrix
- select in or jion
- 【COderForces】OR in Matrix
- in、or、exists区别
- web or app in Mobile ?
- web or app in Mobile ?
- python in or of opencv
- LuaPlus学习
- Android-BaseLine框架初识之如何使用(二)
- MAX方法
- 看了下ImageLoader框架发表下自己的理解
- ThinkPad E450 10.11 驱动HD4400的注意即解决方法
- has_key or in
- docker 学习笔记4
- onclientclick和onclick区别
- 何值会被判断为false
- 设置平铺的方式拉伸图片
- Android笔记
- 剑指offer-从上往下打印二叉树
- Android项目开发(2)-注册手机验证知识总结
- 【SSH (六)】struts2 整合 spring 并 连接数据库
in
works with 2.6 too right? – Logan Jan 17 '13 at 4:07