bjjvvv
9/24/2016 - 5:49 AM

v2ex_308543.py

from collections import defaultdict

INPUT =  [{'id':1, 'abc':'2'}, {'id':1, 'abc':'3'}, {'id':2, 'abc':'2'}]
simplified_inpput = [{item['id']: item['abc']} for item in INPUT] # [{1: '2'}, {1: '3'}, {2: '2'}]

d = defaultdict(list) # 用数组初始化 dict 的 value
for item in simplified_inpput:
   for key, value in item.items(): # 只循环一次
        d[key].append(value)
# d = {1: ['2', '3'], 2: ['2']}

result = [{'id': key, 'abc': value} for key, value in d.items()]

print(result) # [{'id': 1, 'abc': ['2', '3']}, {'id': 2, 'abc': ['2']}]