gpt4 book ai didi

python - 如何在键不一致的字典列表中查找值

转载 作者:行者123 更新时间:2023-11-30 22:39:19 25 4
gpt4 key购买 nike

这里,我有一个字典列表,我需要使用值查找对象。

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 丢失时提供默认值,所以你可以尝试这个:

dict.get

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com