Python 字典属性判断 - 使用 'in' 关键字
在 Python 中,可以使用 'in' 关键字来判断字典中是否存在某个属性。具体实现方法如下:
my_dict = {'name': 'Tom', 'age': 18}
if 'name' in my_dict:
print('my_dict has the attribute 'name'')
else:
print('my_dict does not have the attribute 'name'')
if 'gender' in my_dict:
print('my_dict has the attribute 'gender'')
else:
print('my_dict does not have the attribute 'gender'')
输出结果为:
my_dict has the attribute 'name'
my_dict does not have the attribute 'gender'
其中,第一个 if 语句判断字典 my_dict 中是否存在属性 'name',由于存在,因此输出 'my_dict has the attribute 'name'';第二个 if 语句判断字典 my_dict 中是否存在属性 'gender',由于不存在,因此输出 'my_dict does not have the attribute 'gender''。
原文地址: https://www.cveoy.top/t/topic/f2oB 著作权归作者所有。请勿转载和采集!