📌  相关文章
📜  Python|检查字典中是否存在给定的多个键

📅  最后修改于: 2022-05-13 01:55:03.663000             🧑  作者: Mango

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

Python中的字典由键值对的集合组成。每个键值对将键映射到其关联的值。

让我们讨论检查字典中多个键的各种方法:

方法 #1使用运算符:
这是我们创建一个包含用于比较的键的集合的常用方法,并使用运算符检查该键是否存在于我们的字典中。

# Python3 code to check multiple key existence
# using comparison operator
  
# initializing a dictionary
sports = {"geeksforgeeks" : 1, "practice" : 2, "contribute" :3}
  
# using comparison operator
print(sports.keys() >= {"geeksforgeeks", "practice"})
print(sports.keys() >= {"contribute", "ide"})
输出:
True
False

方法 #2使用 issubset() :
在这种方法中,我们将检查我们必须比较的键是否是字典中键的subset()

# Python3 code heck multiple key existence
# using issubset
  
# initializing a dictionary
sports = {"geeksforgeeks" : 1, "practice" : 2, "contribute" :3}
  
# creating set of keys that we want to compare
s1 = set(['geeksforgeeks', 'practice'])
s2 = set(['geeksforgeeks', 'ide'])
  
print(s1.issubset(sports.keys()))
print(s2.issubset(sports.keys()))
输出:
True
False

方法 #3使用 if 和 all 语句:
在这个方法中,我们将检查我们想要比较的所有关键元素是否都存在于我们的字典中。

# Python3 code check multiple key existence
# using if and all
  
# initializing a dictionary
sports = {"geeksforgeeks" : 1, "practice" : 2, "contribute" :3}
  
# using if, all statement 
if all(key in sports for key in ('geeksforgeeks', 'practice')):
    print("keys are present")
else:
    print("keys are not present")
  
# using if, all statement 
if all(key in sports for key in ('geeksforgeeks', 'ide')):
    print("keys are present")
else:
    print("keys are not present")
输出:
keys are present
keys are not present