[226]python字典(Dictionary)has_key()方法

has_key()方法

描述

Python 字典(Dictionary) has_key() 函数用于判断键是否存在于字典中,如果键在字典dict里返回true,否则返回false。

语法

has_key()方法语法:

dict.has_key(key)

参数

key – 要在字典中查找的键。

返回值

如果键在字典里返回true,否则返回false。

实例

以下实例展示了 has_key()函数的使用方法:

#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7}

print "Value : %s" %  dict.has_key('Age')
print "Value : %s" %  dict.has_key('Sex')

以上实例输出结果为:

Value : True
Value : False

解决:AttributeError: ‘dict’ object has no attribute ‘has_key’

在使用之前的代码时,报错:

Traceback (most recent call last):
  File "xxx", line xx, in <module>
    print(dict.has_key("name"))
AttributeError: 'dict' object has no attribute 'has_key

经过查阅资料,发现这个错误产生的原因是python3.0之后该方法已经没有了,如果继续使用这个方法,就会报这样的错误。

解决方法

**方法1:**使用 __contains__() 方法

从Python3.x开始,has_key() 函数被 contains(key) 函数替代。

正确的代码是:

print(dict1.__contains__('name'))  

方法二:使用 in 关键字

# 生成一个字典
dict = {'name': '','age': '','sex': ''}
# 判断key是否存在于dict中
print('name' in dict)  # 结果返回True
print('id' in dict)  # 结果返回False

方法三:使用 keys() 方法

# 生成一个字典
dict = {'name': '','age': '','sex': ''}
# 判断是否存在,其中dict.keys()是列出字典所有的key
print('name' in dict.keys())  # 结果返回True
print('id' in dict.keys())  # 结果返回False

Python 3.X 里不包含 has_key() 函数,被 __contains__(key) 替代:

dict3 = {'name':'z','Age':7,'class':'First'};
print("Value : ",dict3.__contains__('name'))
print("Value : ",dict3.__contains__('sex'))

执行结果:

Value :  True
Value :  False

or

if adict.has_key(key1):  
改为

if key1 in adict:  

总结:出现问题多敲一下help()

参考:https://blog.csdn.net/nings666/article/details/135012847

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

周小董

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值