Home > database >  Parsing List of Dictionaries
Parsing List of Dictionaries

Time:03-08

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 "pending" order status in the list of dictionaries. How can I check if any "pending" order status in whole list?

CodePudding user response:

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

CodePudding user response:

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
  • Related