在Python中有各种数据结构,而字典是我们生产中经常会用到的数据结构,这里记录一下如果判断某个key是否存在于字典中的二种方法。
方法一:字典自带属性has_key
Python2下: nock:work nock$ python2.7
Python 2.7.10 (default, Jul 14 , 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 = { ame: ock, age: 18}
>>> user_info.has_key(job)
False
>>> user_info.has_key(age)
True
>>> user_info.has_key( ame)
True
Python3下: nock:work nock$ python3
Python 3.5.1 (default, Dec 26 , 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