Mateus Silva
Mateus Silva

Reputation: 69

Lambda filter a list of dictionaries Python

I started programming with python a little while ago I have a doubt with dictionary

I have this array and I already have a method that gets an id array, I tried with lambda to create a filtered list, My question is if in addition to the filtered list I can leave in the list only the necessary attributes as the example

example:

 ages = [{'employedId': 1, 'age': 22},
         {'employedId': 2, 'age': 32},
         {'employedId': 3, 'age': 17},
         {'employedId': 4, 'age': 53},
         {'employedId': 5, 'age': 32},
         {'employedId': 6, 'age': 22}
         ]
list_filtred = list(filter(lambda tag: tag['age'] == 22, ages))

python output

[{'employedId': 1, 'age': 22}, 
 {'employedId': 6, 'age': 22}]

Can I create a lambda filtering method to have such an output or do I have to work on the array to create a new values ​​list?

expected output

[1,6]

Upvotes: 5

Views: 7142

Answers (3)

Teymour
Teymour

Reputation: 2079

The filter function on its own won't do this, but you can do this using a functional, declarative style (rather than imperative).

For example, to extract all the people whose age is 22

list_filtered = list(filter(lambda tag: tag['age']==22, ages))

Lambda functions are powerful tools; you can construct a variety of conditions.

To get the array in the format you want, try the map function which uses similar principles but instead of filtering an array it applies the result of the function to each item in the array.

list_filtered = list(map(lambda x: x['employedId'], ages))

Upvotes: 2

C.Nivs
C.Nivs

Reputation: 13106

As an alternative leveraging your existing list statement, you could add a map statement that grabs the employedId key:

from operator import itemgetter

list(map(itemgetter('employedId'), filter(lambda tag: tag['age'] == 22, ages)))
[1, 6]

Otherwise, I think @CoryKramer's answer is a bit more readable

Upvotes: 2

Cory Kramer
Cory Kramer

Reputation: 117886

You can use a list comprehension to access the value corresponding to the 'employedId' key after you've used the 'age' for filtering.

>>> [tag['employedId'] for tag in ages if tag['age'] == 22]
[1, 6]

Upvotes: 6

Related Questions