检查给定的多个键是否在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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP