years year0 ID sum 100 year1 ID sum 10 ID sum 20 set for in years for

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
years = {'year0': [{'ID' : 1, 'sum' : 100}], 'year1': [{'ID' : 1, 'sum' : 10}, {'ID' : 2, 'sum' : 20}]}
s = set()
for y in years:
d = {}
for i in years[y]:
s.add(i['ID'])
d[i['ID']] = i['sum']
years[y] = d
def add(d, key, val):
d[key] = val
return d
lst = [reduce(
lambda r, (y, d): add(r, 'sum_%s' %y, d.get(id, 0)),
years.iteritems(),
{'ID' : id}) for id in s]
print lst
# [{'sum_year0': 100, 'ID': 1, 'sum_year1': 10}, {'sum_year0': 0, 'ID': 2, 'sum_year1': 20}]