Python检查字典中是否存在键

时间:2020-02-23 14:42:29  来源:igfitidea点击:

很容易检查Python字典中是否存在键

我们需要使用"in"关键字检查字典中是否存在键。

my_dict = {'one':1,'three':3,'two':2}
if 'three' in my_dict:
    print(my_dict['three'])

因此,我们可以使用if_dict中的'three':检查'三'字符串作为my_dict中的键。
让我们在举例的帮助下了解。

my_dict = {'John':18,'Mohan':23,'Martin':26,'Adam':40}
if 'Martin' in my_dict:
print("Age of employee Martin is: ",my_dict['Martin'])
if 'Mary' in my_dict:
print("Age of employee Mary is: ",my_dict['Mary'])
else:
print("Mary is not key in dictionary my_dict")

输出:

Age of employee Martin is: 26
Mary is not key in dictionary my_dict