has_key or in
2016-03-11 10:12
405 查看
'has_key()'
or 'in'?
up vote393down votefavorite 51 | I wonder what is better to do:d = {'a': 1, 'b': 2} 'a' in d True or: d = {'a': 1, 'b': 2} d.has_key('a') True python
| |||
add a comment |
11 Answers
activeoldestvotesup vote546down voteaccepted | inis definitely more pythonic. In fact has_key()was removed in Python 3.x.
| ||||||||||||||||||||
comment |
up vote179down vote | inwins 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 -mtimeitis SO helpful -- it's not just about saving a hundred nanoseconds here and there!-)
| ||||||||||||
a comment |
up vote43down vote | According to python docs:has_key()is deprecated in favor of key in d.
| ||||
a comment |
up vote28down vote | 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 dictwas introduced).
| ||||||||||||
a comment |
up vote13down vote | There is one example where inactually kills your performance. If you use inon 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 infalls back to a linear search via __getitem__). Fix is obviously trivial: def __contains__(self, x): return self.has_key(x)
| ||
add a comment |
up vote8down vote | has_keyis a dictionary method, but inwill work on any collection, and even when __contains__is missing, inwill use any other method to iterate the collection to find out.
|
相关文章推荐
- 看了下ImageLoader框架发表下自己的理解
- 学习进度条
- iOS学习之UINavigationController
- c中使用gets() 提示warning: this program uses gets(), which is unsafe.
- php strpos返回字符串首次出现的位置
- BLE 广播数据解析
- 做一个合格的程序猿之浅析Spring IoC源码(六)BeanFactoryPostProcessor
- Categroy实例
- 【经典转载】Linux进程学习系列之六 进程控制函数之exec()函数的学习
- Socket通讯实例-基本Socket
- 解决setOnItemClickListener无响应的bug
- java进度条代码
- .NET 程序员十种必备工具
- Android项目开发(1)-登录页面知识总结
- IOS开发 代码获取当前APP的版本号
- 添加长时间监听事件 要点:监听的位置和监听事件名称,本案例用setonlongclicklistener事件
- JSON example
- DOS窗口下找到占用8080端口的进程,并且将该进程结束
- 工具的使用——windows操作系统的使用(三)
- GitHub前100的开源库,非常实用