Reputation: 93
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
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
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
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
Reputation: 164673
Is there a way to do this without using for loops or if conditions
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