Python 2,总结了dict列表中的相同值

时间:2015-09-07 21:07:20

标签: python

我有这样的词:

[{'number': 44, 'code': 'ZXC'},
{'number': 699, 'code': 'ASD'},     
{'number': 3, 'code': 'ZXC'}]

如何获得这样的列表:

[{'number': 47, 'code': 'ZXC'},
{'number': 699, 'code': 'ASD'}]

2 个答案:

答案 0 :(得分:0)

我建议这样做,将yourList视为输入列表:

tempList = list()  
FinalList()=list()  
for d in yourList:  
    if d['day'] in tempList:  
        FinalList[tempList.index(d['day'])]['number'] += d['number']  
    else: 
        tempList.append(d['day')]
        FinalList.append(d)

答案 1 :(得分:0)

试试这个:

data=[{'number': 44, 'code': 'ZXC'},{'number': 699, 'code': 'ASD'},{'number': 3, 'code': 'ZXC'}]

from collections import defaultdict

c = defaultdict(int)
for d in data:
    c[d['code']] += d['number']

print [{'number': number, 'code': code} for number, code in c.items()]
#So:
new_list=[{'number': number, 'code': code} for number, code in c.items()]
#In new_list is your list groupped by code and sum applied.