新聞中心
這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷(xiāo)解決方案
Python 程序:檢查字典中是否存在給定鍵
創(chuàng)新互聯(lián)python教程:

淮陽(yáng)網(wǎng)站建設(shè)公司成都創(chuàng)新互聯(lián),淮陽(yáng)網(wǎng)站設(shè)計(jì)制作,有大型網(wǎng)站制作公司豐富經(jīng)驗(yàn)。已為淮陽(yáng)千余家提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\成都外貿(mào)網(wǎng)站建設(shè)要多少錢(qián),請(qǐng)找那個(gè)售后服務(wù)好的淮陽(yáng)做網(wǎng)站的公司定做!
寫(xiě)一個(gè) Python 程序,用一個(gè)實(shí)際例子來(lái)檢查字典中是否存在給定的鍵。
檢查字典中是否存在給定鍵的 Python 程序示例 1
在這個(gè) python 程序中,我們使用 if 語(yǔ)句和鍵功能來(lái)檢查該鍵是否存在于這個(gè)字典中。如果為真,則打印鍵值。
# 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 程序驗(yàn)證給定的鍵是否存在于字典中示例 2
這個(gè) 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
在這個(gè) python 程序中,我們使用 get 函數(shù)來(lái)檢查密鑰是否存在。
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
>>> 分享名稱(chēng):Python 程序:檢查字典中是否存在給定鍵
新聞來(lái)源:http://fisionsoft.com.cn/article/dhgdigp.html


咨詢(xún)
建站咨詢(xún)
