Parsing List of Dictionaries

Viewed 51

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?

2 Answers

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

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
Related