这里,我有一个字典列表,我需要使用值查找对象。
people = [
{'name': mifta}
{'name': 'khaled', 'age':30},
{'name': 'reshad', 'age':31}
]
我想通过“age”键查找值为 30 的位置。我可以通过以下方式做到这一点
for person in people:
if person.get('age'):
if person['age'] == 30:
有没有更好的方法来做到这一点而不需要大量的 if else ?
最佳答案
您可以只使用 dict.get()
一次,而不使用 person['age']
,它允许您在 key 丢失时提供默认值,所以你可以尝试这个:
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)
关于python - 如何在键不一致的字典列表中查找值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43198765/