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

时间:2014-10-13 16:45:53

标签: python dictionary

在这个词典列表中:

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

我想获得'fruit'密钥值'color'的{​​{1}}密钥值。

我试过了:

'yellow'

我的颜色是唯一的,当它返回any(fruits['color'] == 'yellow' for fruits in lst) 时,我想将True的值设置为所选的水果,在此实例中为fruitChosen

4 个答案:

答案 0 :(得分: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']

答案 1 :(得分:2)

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

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

答案 2 :(得分: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']

答案 3 :(得分:1)

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

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