pythonlistdictionary

Getting a list of values from a list of dicts


I have a list of dicts like this:

[{'value': 'apple', 'blah': 2}, 
 {'value': 'banana', 'blah': 3} , 
 {'value': 'cars', 'blah': 4}]

I want ['apple', 'banana', 'cars']

Whats the best way to do this?


Solution

  • Assuming every dict has a value key, you can write (assuming your list is named l)

    [d['value'] for d in l]
    

    If value might be missing, you can use

    [d['value'] for d in l if 'value' in d]