在Python中有各种数据结构,而字典是我们生产中经常会用到的数据结构,这里记录一下如果判断某个key是否存在于字典中的二种方法。
方法一:字典自带属性has_key
Python2下: nock:work nock$ python2.7
Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> user_info = {'name': 'nock', 'age': 18}
>>> user_info.has_key('job')
False
>>> user_info.has_key('age')
True
>>> user_info.has_key('name')
True
Python3下: nock:work nock$ python3
Python 3.5.1 (default, Dec 26 2015, 18:08:53)
[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> user_info = {'name': 'nock', 'age': 18}
>>> user_info.has_key('job')
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'dict' object has no attribute 'has_key'
>>> user_info.has_key('age')
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'dict' object has no attribute 'has_key'
如上所示可知,字典的has_key方法只能在Python2中使用,在Python3中已经移除。
方法二: in关键字
一般我们刚开始学习认识Python的时候我们都会先字典列表对象的形式把字典所有键返回,再判断该key是否存在于键列表中: nock:work nock$ python3
Python 3.5.1 (default, Dec 26 2015, 18:08:53)
[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> dict_info = {'name': 'nock', 'age': 18}
>>> keys = dict_info.keys()
>>> print(type(keys), keys)
dict_keys(['name', 'age'])
>>> for k in keys:
... if 'name' == k:
... print("key in ok")
... break
...
key in ok
其实这不是最好的方法,那还有更好的方法?
Python2下: nock:work nock$ python2.7
Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> user_info = {'name': 'nock', 'age': 18}
>>> if 'name' in user_info:
... print('in')
...
in
>>> if 'job' not in user_info:
... print('not in')
... else:
... print('in')
...
not in
Python3下: nock:work nock$ python3
Python 3.5.1 (default, Dec 26 2015, 18:08:53)
[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> user_info = {'name': 'nock', 'age': 18}
>>> if 'job' not in user_info:
... print('in')
...
in
>>> if 'job' not in user_info:
... print('not in')
... else:
... print('in')
...
not in
如上可知in关键字在Python2和Python3下都适用。
总结
如上实例可知用in关键字是最nice的方法,同时在字典数据量较大的情况下in也是最快的方法,我这里就不实验了,有兴趣的同学可以实践一下。
本文由 空心菜 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为: Apr 17, 2018 at 01:09 pm