Getting a list of values from a list of dicts

SuperString picture SuperString · Sep 1, 2011 · Viewed 218.2k times · Source

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?

Answer

Ismail Badawi picture Ismail Badawi · Sep 1, 2011

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]