检查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
热门推荐
4 圆圆的祝福语简短
7 短祝福语简短暖心
10 跨年的生日祝福语简短
11 师生聚餐的祝福语简短
12 幼儿狗年祝福语大全简短
13 简短长辈新年祝福语
14 低调祝福语简短10字
15 酒桌升学祝福语简短
16 周末祝福语正能量简短
17 幼师春节祝福语简短创意
18 给长辈祝福语简短大全