检查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