检查给定的多个键是否在Python字典中存在


在使用Python进行数据分析时,我们可能需要验证几个值是否作为键存在于字典中。以便分析的下一部分只能使用作为给定值一部分的键。在本文中,我们将看到如何实现这一点。

使用比较运算符

要检查的值被放入一个集合中。然后将集合的内容与字典的键集合进行比较。>= 符号表示字典中的所有键都存在于给定的值集合中。

示例

 在线演示

Adict = {"Mon":3, "Tue":11,"Wed":6,"Thu":9}
check_keys={"Tue","Thu"}

# Use comaprision
if(Adict.keys()) >= check_keys:
   print("All keys are present")
else:
   print("All keys are not present")
# Check for new keys
check_keys={"Mon","Fri"}
if(Adict.keys()) >= check_keys:
   print("All keys are present")
else:
   print("All keys are not present")

输出

运行以上代码将得到以下结果:

All keys are present
All keys are not present

全部存在

在这种方法中,我们使用for循环来检查字典中是否存在每个值。只有当检查键集中的所有值都存在于给定字典中时,all函数才返回true。

示例

 在线演示

Adict = {"Mon":3, "Tue":11,"Wed":6,"Thu":9}
check_keys={"Tue","Thu"}

# Use all
if all(key in Adict for key in check_keys):
   print("All keys are present")
else:
   print("All keys are not present")
# Check for new keys
check_keys={"Mon","Fri"}
if all(key in Adict for key in check_keys):
   print("All keys are present")
else:
   print("All keys are not present")

输出

运行以上代码将得到以下结果:

All keys are present
All keys are not present

使用子集

在这种方法中,我们将要搜索的值作为一个集合,并验证它是否是字典键的子集。为此,我们使用issubset函数。

示例

 在线演示

Adict = {"Mon":3, "Tue":11,"Wed":6,"Thu":9}
check_keys=set(["Tue","Thu"])

# Use all
if (check_keys.issubset(Adict.keys())):
   print("All keys are present")
else:
   print("All keys are not present")
# Check for new keys
check_keys=set(["Mon","Fri"])
if (check_keys.issubset(Adict.keys())):
   print("All keys are present")
else:
   print("All keys are not present")

输出

运行以上代码将得到以下结果:

All keys are present
All keys are not present

更新于:2020年5月13日

2K+ 次浏览

启动你的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.