Python Program to check if a Given key exists in a Dictionary

使用key()和get()函数编写一个Python程序,通过一个实际示例检查给定键是否存在于字典中。

Python程序:检查给定键是否存在于字典中的示例

在此程序中,我们使用 if 语句keys 函数来检查该键是否存在于此 字典 中。如果为真,它将打印键值。

myDict = {'a': 'apple', 'b': 'Banana' , 'o': 'Orange', 'm': 'Mango'}
print("Dictionary : ", myDict)

key = input("Please enter the Key you want to search for: ")

# Check Whether the Given key exists in a Dictionary or Not
if key in myDict.keys():
    print("\nKey Exists in this Dictionary")
    print("Key = ", key, " and Value = ", myDict[key])
else:
    print("\nKey Does not Exists in this Dictionary")
Program to check if a Given key exists in a Dictionary 1

使用索引检查字典中是否存在键

此程序是检查给定键是否存在于字典中的另一种方法。

myDict = {'a': 'apple', 'b': 'Banana' , 'o': 'Orange', 'm': 'Mango'}
print("Dictionary : ", myDict)

key = input("Please enter the Key you want to search for: ")

# Check Whether the Given key exists in a Dictionary or Not
if key in myDict:
    print("\nKey Exists in this Dictionary")
    print("Key = ", key, " and Value = ", myDict[key])
else:
    print("\nKey Does not Exists in this Dictionary")
Dictionary :  {'a': 'apple', 'b': 'Banana', 'o': 'Orange', 'm': 'Mango'}
Please enter the Key you want to search for: m

Key Exists in this Dictionary
Key =  m  and Value =  Mango
>>> 
Dictionary :  {'a': 'apple', 'b': 'Banana', 'o': 'Orange', 'm': 'Mango'}
Please enter the Key you want to search for: g

Key Does not Exists in this Dictionary
>>> 

使用get函数查找字典中是否存在键

在此 程序 中,我们使用 get函数 来检查键是否存在。有关更多信息,请参阅 Python 页面。

myDict = {'a': 'apple', 'b': 'Banana' , 'o': 'Orange', 'm': 'Mango'}
print("Dictionary : ", myDict)

key = input("Please enter the Key you want to search for: ")

# Check Whether the Given key exists in a Dictionary or Not
if myDict.get(key) != None:
    print("\nKey Exists in this Dictionary")
    print("Key = ", key, " and Value = ", myDict[key])
else:
    print("\nKey Does not Exists in this Dictionary")
check if a given key exists in a Dictionary using get function