How do I extract all the values of a specific key from a list of dictionaries?

后端 未结 3 2042
悲哀的现实
悲哀的现实 2020-11-29 08:20

I have a list of dictionaries that all have the same structure within the list. For example:

test_data = [{\'id\':1, \'value\':\'one\'}, {\'id\':2, \'value\         


        
相关标签:
3条回答
  • 2020-11-29 08:40

    You can do this:

    result = map (lambda x:x['value'],test_data)
    
    0 讨论(0)
  • 2020-11-29 08:42

    If you just need to iterate over the values once, use the generator expression:

    generator = ( item['value'] for item in test_data )
    
    ...
    
    for i in generator:
        do_something(i)
    

    Another (esoteric) option might be to use map with itemgetter - it could be slightly faster than the generator expression, or not, depending on circumstances:

    from operator import itemgetter
    
    generator = map(itemgetter('value'), test_data)
    

    And if you absolutely need a list, a list comprehension is faster than iterated list.append, thus:

    results = [ item['value'] for item in test_data ]
    
    0 讨论(0)
  • 2020-11-29 09:02

    If your data is truly large, a generator will be more efficient:

    list((object['value'] for object in test_data))
    

    ex:

    >>> list((object['value'] for object in test_data))
    ['one', 'two', 'three']
    

    The generator portion is this:

    (object['value'] for object in test_data)
    

    By wrapping that in a list(), you exhaust the generator and return its values nicely in an array.

    0 讨论(0)
提交回复
热议问题