您的位置:

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

写一个 Python 程序,用一个实际例子来检查字典中是否存在给定的键。

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

在这个 python 程序中,我们使用 if 语句和键功能来检查该键是否存在于这个字典中。如果为真,则打印键值。

# 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
>>>