Getting a list of values from a list of dicts

前端 未结 9 714
执念已碎
执念已碎 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:27

    Here's another way to do it using map() and lambda functions:

    >>> map(lambda d: d['value'], l)
    

    where l is the list. I see this way "sexiest", but I would do it using the list comprehension.

    Update: In case that 'value' might be missing as a key use:

    >>> map(lambda d: d.get('value', 'default value'), l)
    

    Update: I'm also not a big fan of lambdas, I prefer to name things... this is how I would do it with that in mind:

    >>> import operator
    >>> map(operator.itemgetter('value'), l)
    

    I would even go further and create a sole function that explicitly says what I want to achieve:

    >>> import operator, functools
    >>> get_values = functools.partial(map, operator.itemgetter('value'))
    >>> get_values(l)
    ... []
    

    With Python 3, since map returns an iterator, use list to return a list, e.g. list(map(operator.itemgetter('value'), l)).

提交回复
热议问题