Search code examples
pythonlistdictionary

How to get a value from a dict in a list of dicts


In this list of dicts:

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

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

I tried:

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

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.


Solution

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

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

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

    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!
    

    Demo:

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