ITPub博客

首页 > IT职业 > IT图书 > python判断键在不在字典里

python判断键在不在字典里

IT图书 作者:adder 时间:2021-09-11 10:33:15 0 删除 编辑

python3 中采用 in 方法

#判断字典中某个键是否存在
arr = {"int":"整数","float":"浮点","str":"字符串","list":"列表","tuple":"元组","dict":"字典","set":"集合"}
#使用 in 方法
if "int" in arr:
    print("存在")
if "float" in arr.keys():
    print("存在")
#判断键不存在
if "floats" not in arr:
    print("不存在")
if "floats" not in arr:
    print("不存在")

python 3中不支持 has_key(),python2 中支持

#判断字典中某个键是否存在
arr = {"int":"整数","float":"浮点","str":"字符串","list":"列表","tuple":"元组","dict":"字典","set":"集合"}
#使用自带的has_key()
if(arr.has_key("int")):
    print("存在")

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1595/viewspace-2836574/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-15

  • 博文量
    110
  • 访问量
    723