如何基于一键python合并字典列表

时间:2021-06-30 06:07:29

标签: python list dictionary dataset itertools

我有这个字典列表:

list1 = [
    {'id': 1, 'fop': 192, 'fop_plan': 'capo', 'fup_comments': None},
    {'id': 1, 'fop': 222, 'fop_plan': 'groso', 'fup_comments': None},
    {'id': 2, 'fop': 222, 'fop_plan': 'bien', 'fup_comments': None},
    {'id': 2, 'fop': 222, 'fop_plan': 'bien', 'fup_comments': None},
    {'id': 3, 'fop': 223, 'fop_plan': 'bien', 'fup_comments': None}
]

我想得到这个:

list2 = [
    {'id': 1, 'fop': [192, 222] 'fop_plan': ['capo', 'groso'], 'fup_comments': [None, None]},
    {'id': 2, 'fop': [222, 222], 'fop_plan': ['bien', 'bien'], 'fup_comments': [None, None]},
    {'id': 3, 'fop': 223, 'fop_plan': 'bien', 'fup_comments': None}
]

1 个答案:

答案 0 :(得分:1)

以下内容将起作用。为方便起见,这里使用 itertools.groupby(假设数据按 id 排序)、operator.itemgetterdict.setdefault

from operator import itemgetter
from itertools import groupby

list2 = []

for k, g in groupby(list1, key=itemgetter("id")):
    new_d = {"id": k}
    for d in g:
        for k, v in d.items():
            if k != "id":
                new_d.setdefault(k, []).append(v)
    list2.append(new_d)

# [{'fop': [192, 222],
#   'fop_plan': ['capo', 'groso'],
#   'fup_comments': [None, None],
#   'id': 1},
#  {'fop': [222, 222],
#   'fop_plan': ['bien', 'bien'],
#   'fup_comments': [None, None],
#   'id': 2},
#  {'fop': [223], 'fop_plan': ['bien'], 'fup_comments': [None], 'id': 3}]
相关问题