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

2024-09-29 21:46:52 发布

您现在位置:Python中文网/ 问答频道 /正文

在这里,我有一个字典列表,我需要找到使用值的对象。你知道吗

people = [
   {'name': mifta}
   {'name': 'khaled', 'age':30},
   {'name': 'reshad', 'age':31}
]

我想按“年龄”查找值为30的键。我可以按下面的方法来做

for person in people:
  if person.get('age'):
    if person['age'] == 30:

有没有更好的方法来做到这一点,如果没有很多别的?你知道吗


Tags: 对象方法namein列表forageif
2条回答

您可以只使用dict.get()一次而不使用person['age'],它允许您在缺少键时提供默认值,因此您可以尝试以下操作:

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)

如果要避免If..else,可以使用lambda函数。你知道吗

fieldMatch = filter(lambda x: 30 == x.get('age'), people)

或者也可以使用列表理解来获取列表中的名称。你知道吗

names = [person['name'] for person in people if person.get('age') == 30]

相关问题 更多 >

    热门问题