Return the value for key if key is in the dictionary, else default. If
default is not given, it defaults to None, so that this method never
raises a KeyError
people = [
{'name': 'mifta'},
{'name': 'khaled', 'age':30},
{'name': 'reshad', 'age':31}
]
for person in people:
if person.get('age',0)==30:
print(person)
您可以只使用
dict.get()
一次而不使用person['age']
,它允许您在缺少键时提供默认值,因此您可以尝试以下操作:dict.get
如果要避免If..else,可以使用lambda函数。你知道吗
或者也可以使用列表理解来获取列表中的名称。你知道吗
相关问题 更多 >
编程相关推荐