寫一個 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
>>>
原創文章,作者:OUVXN,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/331231.html