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

pythonserver side programmingprogramming更新于 2025/12/25 23:40:17

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

使用比较运算符

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

示例

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

# 使用比较
if(Adict.keys()) >= check_keys:
   print("All keys are present")
else:
   print("All keys are not present")
# 检查新键
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

使用 all

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

示例

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

# 使用 all
if all(key in Adict for key in check_keys):
   print("All keys are present")
else:
   print("所有键均不存在")
# 检查新键
check_keys={"Mon","Fri"}
if all(key in Adict for key in check_keys):
   print("所有键均存在")
else:
   print("所有键均不存在")

输出

运行上述代码得到以下结果 −

所有键均存在
所有键均不存在

使用子集

在此方法中,我们将要搜索的值作为一个集合,并验证它是否是字典中键的子集。为此,我们使用 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

相关文章


有用资源