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

创新互联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
>>>

网页题目:Python 程序:检查字典中是否存在给定键
新闻来源:http://www.shufengxianlan.com/qtweb/news46/304996.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联