写一个 Python示例,用一个实际例子来检查字典中是否存在给定的键。
在这个 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示例是检查给定键是否存在于字典中的另一种方法。
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 程序中,我们使用 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
>>>
标签: 百度统计