簡體   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