AxlTylerThomas
AxlTylerThomas

Reputation: 93

get a list of specific value from a list of dictionaries without using for loops or if conditions only if necessary

Say I have a list of dictionaries.

listOfDict = [{"name": "Joel","Age": "10","Grade": "A"},{"name": "Adam","Age": "11","Grade": "B"},{"name": "Rachel","Age": "10","Grade": "B"}]

I want to get a list of names whose age is 10. So output would look like this.

listOfNames = ["Joel", "Rachel"]

Is there a way to do this without using for loops or if conditions. I tried to use Lambda function but to no avail.

Upvotes: 3

Views: 83

Answers (4)

Vasilis G.
Vasilis G.

Reputation: 7844

There is a way to use lambda functions, along with map and filter to get your desired result without using neither for loop or if condition, but the code will be a bit difficult to read:

listOfDict = [{"name": "Joel","Age": "10","Grade": "A"},{"name": "Adam","Age": "11","Grade": "B"},{"name": "Rachel","Age": "10","Grade": "B"}]

listOfNames = list(map(lambda elem: elem['name'], list(filter(lambda elem: elem['Age']=="10",listOfDict))))

print(listOfNames)

Result:

['Joel', 'Rachel']

Upvotes: 1

Ricky Kim
Ricky Kim

Reputation: 2022

No for loops or if conditions using pandas.DataFrame:

import pandas as pd
df=pd.DataFrame.from_dict(listOfDict)
result=df[df['Age']=='10']['name'].tolist()

OUTPUT

['Joel', 'Rachel']

Upvotes: 1

devkingsejong
devkingsejong

Reputation: 76

This works.

Using lambda:

result = list(map(lambda x: x['name'] if x['Age'] == "10" else None, listOfDict ))
result = [x for x in result if x is not None]
print(result)

Upvotes: 1

jpp
jpp

Reputation: 164673

Is there a way to do this without using for loops or if conditions

No, there isn't!

Use a loop. It's unavoidable at some level. Using a list comprehension:

res = [d['name'] for d in listOfDict if d['Age'] == '10']

Upvotes: 4

Related Questions