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



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

in list of dicts:

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

i want value of 'fruit' key 'color' key's value 'yellow'.

i tried:

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

my colors unique , when returns true want set value of fruitchosen selected fruit, 'melon' in instance.

you utilize next() function generator expression:

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

this assign first fruit dictionary match fruit_chosen, or none if there no match.

alternatively, if leave out default value, next() raise stopiteration if no match found:

try: fruit_chosen = next(fruit['fruit'] 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'] fruit in lst if fruit['color'] == 'yellow'), none) 'melon' >>> next((fruit['fruit'] fruit in lst if fruit['color'] == 'maroon'), none) none true >>> next(fruit['fruit'] fruit in lst if fruit['color'] == 'maroon') traceback (most recent phone call last): file "<stdin>", line 1, in <module> stopiteration

python dictionary

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -