判断是否为python关键字_如何判断Python字典中是否存在某个key

在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也是最快的方法,我这里就不实验了,有兴趣的同学可以实践一下。

zan.png

本文由 空心菜 创作,采用 知识共享署名4.0 国际许可协议进行许可

本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名

最后编辑时间为: Apr 17, 2018 at 01:09 pm

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值