如何从dict列表中的dict获取值



在此dicts列表中:

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

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

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

这将指定第一个水果字典与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

如果您确信'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']

我认为filter更适合这种情况。

result = [fruits['fruit'] for fruits in filter(lambda x: x['color'] == 'yellow', lst)]

最新更新