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

问题描述 投票:0回答:4

在此字典列表中:

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'

python list dictionary
4个回答
4
投票

您可以使用列表理解来获取所有黄色水果的列表。

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

3
投票

您可以将

next()
函数与生成器表达式一起使用:

fruit_chosen = next((fruit['fruit'] for fruit in lst if fruit['color'] == 'yellow'), None)

这将分配 first 水果字典来匹配

fruit_chosen
,如果没有匹配则分配
None

或者,如果您省略默认值,如果未找到匹配项,

next()
将引发
StopIteration

try:
    fruit_chosen = next(fruit['fruit'] for fruit in lst if fruit['color'] == 'yellow')
except StopIteration:
    # No matching fruit!

演示:

>>> lst = [{'fruit': 'apple', 'qty':'4', 'color': 'green'},{'fruit': 'orange', 'qty':'6', 'color': 'orange'},{'fruit': 'melon', 'qty':'2', 'color': 'yellow'}]
>>> next((fruit['fruit'] for fruit in lst if fruit['color'] == 'yellow'), None)
'melon'
>>> next((fruit['fruit'] for fruit in lst if fruit['color'] == 'maroon'), None) is None
True
>>> next(fruit['fruit'] for fruit in lst if fruit['color'] == 'maroon')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

2
投票

如果您确定

'color'
键是唯一的,您可以轻松构建字典映射
{color: fruit}
:

>>> lst = [{'fruit': 'apple', 'qty':'4', 'color': 'green'},
           {'fruit': 'orange', 'qty':'6', 'color': 'orange'},
           {'fruit': 'melon', 'qty':'2', 'color': 'yellow'}]
>>> dct = {f['color']: f['fruit'] for f in lst}
>>> dct
{'orange': 'orange', 'green': 'apple', 'yellow': 'melon'}

这使您可以快速有效地分配例如

fruitChosen = dct['yellow']

1
投票

我认为

filter
更适合这种情况。

result = [fruits['fruit'] for fruits in filter(lambda x: x['color'] == 'yellow', lst)]
© www.soinside.com 2019 - 2024. All rights reserved.