簡體   English   中英

如何基於一鍵python合並字典列表

[英]how to merge a list of dicts based on one key python

我有這個字典列表:

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}
]

以下內容將起作用。 這使用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}]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM