list of multiple dicts

Question:

I have the following list of dictonories

list = [{'color': 'yellow', 'isvalid': '1'}, {'color': 'red', 'isvalid': '0'}, {'color': 'green', 'isvalid': '1'}]

I want to check if ‘color = red and isvalid = 1’ and ‘color = green and isvalid = 1’.

Lets say I want to check if color=green and isvalid =1 only when color=red and isvalid=1

I tried the following and a better method than the following.


count = 0
for i in list:
    if (i['color'] == 'red' or i['color'] == 'green') and i[valid] == '1':
        count += 1

if count == 2:

    print("expected colors are valid in set")
else:

    print("expected colors are not valid in set")
Asked By: ecstasy

||

Answers:

This appears to be what you’re after:

dicts = [{'color': 'yellow', 'isvalid': '1'}, {'color': 'red', 'isvalid': '0'}, {'color': 'green', 'isvalid': '1'}]

check_colors = ['red', 'green']

result = all(any(d['isvalid'] == '1' for d in dicts if d['color'] == c) for c in check_colors)

print(result)

# set 'isvalid' for the 'red' one to '1'
dicts[1]['isvalid'] = '1'

# try again
result = all(any(d['isvalid'] == '1' for d in dicts if d['color'] == c) for c in check_colors)

print(result)

Result:

False
True
Answered By: Grismar
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.