检查Python字典中是否已经存在给定的键
在Python中给定一个字典,编写一个Python程序来检查给定的键是否已经存在于字典中。如果存在,则打印“Present”和键的值。否则打印“不存在”。
例子:
Input : {'a': 100, 'b':200, 'c':300}, key = b
Output : Present, value = 200
Input : {'x': 25, 'y':18, 'z':45}, key = w
Output : Not present
方法 #1:使用内置方法keys()
keys()
方法返回字典中所有可用键的列表。使用内置方法keys()
,使用 if 语句和 'in'运算符来检查键是否存在于字典中。
# Python3 Program to check whether a
# given key already exists in a dictionary.
# Function to print sum
def checkKey(dict, key):
if key in dict.keys():
print("Present, ", end =" ")
print("value =", dict[key])
else:
print("Not present")
# Driver Code
dict = {'a': 100, 'b':200, 'c':300}
key = 'b'
checkKey(dict, key)
key = 'w'
checkKey(dict, key)
输出:
Present, value = 200
Not present
方法 #2:使用if
和in
此方法仅使用if
语句来检查给定键是否存在于字典中。
# Python3 Program to check whether a
# given key already exists in a dictionary.
# Function to print sum
def checkKey(dict, key):
if key in dict:
print("Present, ", end =" ")
print("value =", dict[key])
else:
print("Not present")
# Driver Code
dict = {'a': 100, 'b':200, 'c':300}
key = 'b'
checkKey(dict, key)
key = 'w'
checkKey(dict, key)
输出:
Present, value = 200
Not present
方法#3:使用内置方法has_key()
如果给定的键在字典中可用, has_key()
方法返回 true,否则返回 false。使用内置方法has_key()
,使用 if 语句检查键是否存在于字典中。
注意 – has_keys()
方法已从 Python3 版本中删除。因此,它只能在 Python2 中使用。
# Python3 Program to check whether a
# given key already exists in a dictionary.
# Function to print sum
def checkKey(dict, key):
if dict.has_key(key):
print "Present, value =", dict[key]
else:
print "Not present"
# Driver Function
dict = {'a': 100, 'b':200, 'c':300}
key = 'b'
checkKey(dict, key)
key = 'w'
checkKey(dict, key)
输出:
Present, value = 200
Not present