Reputation: 3731
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.
Upvotes: 2
Views: 351
Reputation: 122152
If you're certain that the 'color'
keys will be unique, you can easily build a dictionary mapping {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'}
This allows you to quickly and efficiently assign e.g.
fruitChosen = dct['yellow']
Upvotes: 2
Reputation: 54243
I think filter
fits better in this context.
result = [fruits['fruit'] for fruits in filter(lambda x: x['color'] == 'yellow', lst)]
Upvotes: 1
Reputation: 1124988
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
Upvotes: 3
Reputation: 118021
You can use a list comprehension to get a list of all the fruits that are yellow.
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']
Upvotes: 4