Python - Flatten the list of dictionaries

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

List of dictionaries:

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


        
4条回答
  •  半阙折子戏
    2021-01-01 10:45

    You can do this with 2 nested loops, and dict.update() to add inner dictionaries to a temporary dictionary and add it at the end:

    L = []
    for d in data:
        temp = {}
        for key in d:
            temp.update(d[key])
    
        L.append(temp)
    
    # timeit ~1.4
    print(L)
    

    Which Outputs:

    [{'l': 'Apple', 'b': 'Milk', 'd': 'Meatball', 'favourite': 'coke', 'dislike': 'juice'}, {'l': 'Apple1', 'b': 'Milk1', 'd': 'Meatball2', 'favourite': 'coke2', 'dislike': 'juice3'}]
    

提交回复
热议问题