Getting a list of values from a list of dicts

前端 未结 9 754
执念已碎
执念已碎 2020-11-22 15:22

I have a list of dicts like this:

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


        
9条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 15:45

    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]
    

提交回复
热议问题