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
Solution 1:
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']
Solution 2:
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) isNone
True
>>>next(fruit['fruit'] for fruit in lst if fruit['color'] == 'maroon')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
Solution 3:
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']
Solution 4:
I think filter
fits better in this context.
result = [fruits['fruit'] for fruits in filter(lambda x: x['color'] == 'yellow', lst)]
Post a Comment for "How To Get A Value From A Dict In A List Of Dicts"