Python - Flatten the list of dictionaries

后端 未结 4 1339
情话喂你
情话喂你 2021-01-01 09:54

List of dictionaries:

data = [{
         \'a\':{\'l\':\'Apple\',
                \'b\':\'Milk\',
                \'d\':\'Meatball\'},
         \'b\':{\'favou         


        
4条回答
  •  我在风中等你
    2021-01-01 10:46

    You can do the following, using itertools.chain:

    >>> from itertools import chain
    # timeit: ~3.40
    >>> [dict(chain(*map(dict.items, d.values()))) for d in data]
    [{'l': 'Apple', 
      'b': 'Milk', 
      'd': 'Meatball', 
      'favourite': 'coke', 
      'dislike': 'juice'}, 
     {'l': 'Apple1', 
      'b': 'Milk1', 
      'dislike': 'juice3', 
      'favourite': 'coke2', 
      'd': 'Meatball2'}]
    

    The usage of chain, map, * make this expression a shorthand for the following doubly nested comprehension which actually performs better on my system (Python 3.5.2) and isn't that much longer:

    # timeit: ~2.04
    [{k: v for x in d.values() for k, v in x.items()} for d in data]
    # Or, not using items, but lookup by key
    # timeit: ~1.67
    [{k: x[k] for x in d.values() for k in x} for d in data]
    

    Note:

    RoadRunner's loop-and-update approach outperforms both these one-liners at timeit: ~1.37

提交回复
热议问题