Md Khaled Hossain
Md Khaled Hossain

Reputation: 65

how to find value in list of dictionaries where keys are not consistent

here, I have a list of dictionaries, I need to find the object using value.

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

I would like to find by 'age' key where value is 30. I can do this by following way

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

is there any better way to do this without lots of if else?

Upvotes: 1

Views: 57

Answers (2)

ns15
ns15

Reputation: 8754

If you want to avoid if..else you can use lambda function.

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

or also use list comprehension to get names in a list.

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

Upvotes: 1

McGrady
McGrady

Reputation: 11477

You can just use dict.get() one time without person['age'], it allows you to provide a default value if the key is missing, so you can try this:

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)

Upvotes: 2

Related Questions