在这个字典列表中:
lst = [{'fruit': 'apple', 'qty':'4', 'color': 'green'},
{'fruit': 'orange', 'qty':'6', 'color': 'orange'},
{'fruit': 'melon', 'qty':'2', 'color': 'yellow'}]
我想获得 'fruit' 的值'color' 所在的键键的值为 'yellow' .
我试过:
any(fruits['color'] == 'yellow' for fruits in lst)
我的颜色是独一无二的,当它返回时True我想设置 fruitChosen 的值到选定的水果,这将是'melon'在这种情况下。
请您参考如下方法:
您可以使用列表理解来获取所有黄色水果的列表。
lst = [{'fruit': 'apple', 'qty':'4', 'color': 'green'},
{'fruit': 'orange', 'qty':'6', 'color': 'orange'},
{'fruit': 'melon', 'qty':'2', 'color': 'yellow'}]
>>> [i['fruit'] for i in lst if i['color'] == 'yellow']
['melon']
