我有这个字典列表:
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}
]
答案 0 :(得分:1)
以下内容将起作用。为方便起见,这里使用 itertools.groupby
(假设数据按 id 排序)、operator.itemgetter
和 dict.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}]