DGL
DGL

Reputation: 53

How to filter dictionary inside a list by its value matching a condition?

I have the code as follows

result = [{"origin_location":'original', 'service':'amazon'},
          {'origin_location':'duplicate', 'service':'flipkart'}]

What I want is the result as

[{'origin_location':'duplicate', 'service':'flipkart'}]

ie, get only those list items where service is flipkart.

I've tried my code for this as follows

result = filter(lambda x: (line['service'] for line in result) == 'flipkart', result)
print ("Result= ", result)

But it displays [] only. How to correct my code to get the correct output? Thanks in advance.

Upvotes: 1

Views: 190

Answers (2)

jpp
jpp

Reputation: 164693

filter works on an iterable. In Python 2.7, it will return a list, while in Python 3.x you have an iterable which can wrapped into a list.

So, for example, you do not need a for loop within your filter statement:

lst = [{'origin_location':'original', 'service':'amazon'},
       {'origin_location':'duplicate', 'service':'flipkart'}]

result = list(filter(lambda x: x['service'] == 'flipkart', lst))

print("Result= ", result)

# Result=  [{'origin_location': 'duplicate', 'service': 'flipkart'}]

The lambda function is applied to each element in lst; if it returns False the element is "filtered" out.

Note the logic can be implemented more efficiently via a list comprehension:

result = [i for i in lst if i['service'] == 'flipkart']

If you need to replicate the laziness of filter, use a generator expression (...) instead.

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 117886

You can use a list comprehension to only keep the items with this condition

>>> result = [i for i in result if i.get('service') == 'flipkart']
>>> result
[{'origin_location': 'duplicate', 'service': 'flipkart'}]

Upvotes: 2

Related Questions