如何从字典列表中的字典中获取值 [英] How to get a value from a dict in a list of dicts

查看:687
本文介绍了如何从字典列表中的字典中获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此字典列表中:

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

我想获取'fruit'键的值,其中'color'键的值是'yellow'.

I want to get the value of the 'fruit' key where the 'color' key's value is 'yellow'.

我尝试过:

any(fruits['color'] == 'yellow' for fruits in lst)

我的颜色是唯一的,当它返回True时,我想将fruitChosen的值设置为所选水果,在这种情况下为'melon'.

My colors are unique and when it returns True I want to set the value of fruitChosen to the selected fruit, which would be 'melon' in this instance.

推荐答案

您可以使用

You could use the next() function with a generator expression:

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

这会将 first 水果字典分配为与fruit_chosen匹配,如果没有匹配,则为None.

This will assign the first fruit dictionary to match to fruit_chosen, or None if there is no match.

或者,如果省略默认值,则如果找不到匹配项,则next()将提高StopIteration:

Alternatively, if you leave out the default value, next() will raise StopIteration if no match is found:

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

这篇关于如何从字典列表中的字典中获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆