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

发布时间:2022-07-24

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

在这个 Python 程序中,我们使用 if 语句和 keys() 方法来检查某个键是否存在于字典中。如果存在,则打印对应的键值。

# Python Program to check if a Given key exists in a Dictionary
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")

Python 程序验证给定的键是否存在于字典中示例 2

这个 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 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
>>> 

检查字典中是否存在键的 Python 程序示例 3

在这个 Python 程序中,我们使用 get 方法来检查键是否存在。

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")
Dictionary :  {'a': 'apple', 'b': 'Banana', 'o': 'Orange', 'm': 'Mango'}
Please enter the Key you want to search for: a
Key Exists in this Dictionary
Key =  a  and Value =  apple
>>> 
Dictionary :  {'a': 'apple', 'b': 'Banana', 'o': 'Orange', 'm': 'Mango'}
Please enter the Key you want to search for: x
Key Does not Exists in this Dictionary
>>>