当前分类:300例题>>正文

Python示例:检查字典中是否存在给定键

来源:互联网   更新时间:2023年6月24日  

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
>>> 
本文固定链接:https://6yhj.com/leku-p-4435.html  版权所有,转载请保留本地址!
[猜你喜欢]

标签: 百度统计