gpt4 book ai didi

python - 如何从字典列表中的字典中获取值

转载 作者:太空宇宙 更新时间:2023-11-04 07:08:40 25 4
gpt4 key购买 nike

在这个字典列表中:

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']

关于python - 如何从字典列表中的字典中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26344934/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com