WordPress网站建设宣传图片

Python 字典判断键是否存在

释放双眼,带上耳机,听听看~!

Python 字典判断键是否存在可以使用has_key()方法__contains__(key)方法in 操作符。下面是详细介绍和实例代码:

has_key()方法

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

注意:Python 3.X 不支持该方法。

语法

has_key()方法语法:

dict.has_key(key)

参数

  • key — 要在字典中查找的键。

返回值

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

实例代码

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

tinydict = {'Name': 'Zara', 'Age': 7}
print "Value : %s" %  tinydict.has_key('Age')
print "Value : %s" %  tinydict.has_key('Sex')

以上实例输出结果为:

Value : True
Value : False

python3.x版本相关功能代码/解决方式

__contains__(key)

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

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

执行结果:

Value :  True
Value :  False

in 操作符

test_dict = {'name': 'z', 'Age': 7, 'class': 'First'}
if "user_id" in test_dict:
    print(test_dict["user_id"])
else:
    result = "user_id" in test_dict
    print(result)

if "name" in test_dict:
    result = "name" in test_dict
    print(result)
    print(test_dict["name"])
else:
    print('hello python')

执行结果:

False
True
z

参考内容及更多python字典的相关内容:

Python 字典(Dictionary) | 菜鸟教程

Python 字典(Dictionary) has_key()方法 | 菜鸟教程

给TA打赏
共{{data.count}}人
人已打赏
Python笔记

python爬虫报错:(Caused by SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:1129)')))解决

2022-6-26 22:42:04

Python笔记

python 从列表中随机获取元素方法

2022-7-9 1:49:02

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索
展开目录