多个字典的列表



我有以下字典列表

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

我想检查'color = red and isvalid = 1'和'color = green and isvalid = 1'。

假设我想检查color=green and isvalid=1是否只有当color=red and isvalid=1

我尝试了下面的方法和一个比下面更好的方法。


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")

这似乎是你想要的:

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)

结果:

False
True

相关内容

  • 没有找到相关文章

最新更新