繁体   English   中英

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

[英]How to get a value from a dict in a list of 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 ,如果没有匹配fruit_chosenfruit_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)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM