如何从具有相同ID的字典中​​收集列表?

时间:2017-06-09 18:36:12

标签: python-3.x

[{'id': 6, 'name': 'Jorge'}, {'id': 6, 'name': 'Matthews'}, {'id': 6, 'name': 'Matthews'}, {'id': 7, 'name': 'Christine'}, {'id': 7, 'name': 'Smith'}, {'id': 7, 'name': 'Chris'}]

我想收集具有相同ID的列表

[{'id': 6, 'name': ['Jorge','Matthews','Matthews']}, {'id': 7, 'name': ['Christine','Smith','Chris']}]

2 个答案:

答案 0 :(得分:2)

L = [{'id': 6, 'name': 'Jorge'}, {'id': 6, 'name': 'Matthews'}, {'id': 6, 'name': 'Matthews'}, {'id': 7, 'name': 'Christine'}, {'id': 7, 'name': 'Smith'}, {'id': 7, 'name': 'Chris'}]


temp = {}
for d in L:
    if d['id'] not in temp:
        temp[d['id']] = []
    temp[d['id']].append(d['name'])

answer = []
for k in sorted(temp):
    answer.append({'id':k, 'name':temp[k]})

答案 1 :(得分:0)

您可以使用itertools.groupby对所有id进行分组,然后只为组中的每个元素提取name

In [1]:
import itertools as it
import operator as op

L = [{'id': 6, 'name': 'Jorge'}, ...]

_id = op.itemgetter('id')
[{'id':k, 'name':[e['name'] for e in g]} for k, g in it.groupby(sorted(L, key=_id), key=_id)]

Out[1]:
[{'id': 6, 'name': ['Jorge', 'Matthews', 'Matthews']}, 
 {'id': 7, 'name': ['Christine', 'Smith', 'Chris']}]