sam
sam

Reputation: 19164

Parsing List of Dictionaries

I have a list of dictionaries:

l =  [{'variety': 'NORMAL', 'orderstatus': ‘pass’} , {'variety': 'NORMAL', 'orderstatus': ‘pass’},  {'variety': 'NORMAL', 'orderstatus': ‘pass’,},{'variety': 'NORMAL', 'orderstatus': ‘pending’}]

I want to check if there are any dictionaries with a "pending" order status in the list of dictionaries. How can I check if there are any dictionaries with a "pending" order status in the whole list?

Upvotes: 1

Views: 87

Answers (2)

BrokenBenchmark
BrokenBenchmark

Reputation: 19243

You can use map() to transform the list into a list of booleans, where an element is True only if its corresponding dictionary has an order status of pending. Then, use any() to see if any of the generated booleans are True:

data =  [{'variety': 'NORMAL', 'orderstatus': 'pass'} , {'variety': 'NORMAL', 'orderstatus': 'pass'},  {'variety': 'NORMAL', 'orderstatus': 'pass',},{'variety': 'NORMAL', 'orderstatus': 'pending'}]

print(any(map(lambda x: x['orderstatus'] == 'pending', data))) # Prints True

Upvotes: 2

Tasnuva Leeya
Tasnuva Leeya

Reputation: 2795

use list comprehension:

res = [i for i in l if i['orderstatus'] == 'pending']
print(res)

or using loop:

for i in l:
    if i['orderstatus']:
        # do something

Upvotes: 1

Related Questions