Dict list for aggregated dict list

I am looking for a pythonic / elegant way to convert my dict list (e.g. LD) to an aggregated dict list (e.g., DD). The dict element LDhas id, resultand countas keys, and there can be several dict with the same idwith different results. As a result, the dict DDshould merge idtogether and display everything resulttogether (in results).

Here is an example:

LD = [
    {'id':1, 'result': 'passed', 'count': 10},
    {'id':1, 'result': 'failed', 'count': 20},
    {'id':2, 'result': 'failed', 'count': 100}
]

Here is the result I want

DD = [
    {'id':1, 'results': {'passed': 10, 'failed': 20}},
    {'id':2, 'results': {'passed': 10}}
] 

I could create a for and output dict loop to process each element in LD, but I am wondering if this can be done in single line space using things like zipetc.

Thanks in advance!

+4
2

itertools.groupby:

import itertools
LD = [
{'id':1, 'result': 'passed', 'count': 10},
{'id':1, 'result': 'failed', 'count': 20},
{'id':2, 'result': 'failed', 'count': 100}
]
new_result = [(a, list(b)) for a, b in itertools.groupby(sorted(LD, key=lambda x:x['id']), key=lambda x:x['id'])]
last_result = [{**{'id':a}, **{'results':{i['result']:i['count'] for i in b}}} for a, b in new_result]

:

[{'id': 1, 'results': {'failed': 20, 'passed': 10}}, {'id': 2, 'results': {'failed': 100}}]

: Python2:

new_result = [(a, list(b)) for a, b in itertools.groupby(sorted(LD, key=lambda x:x['id']), key=lambda x:x['id'])]
last_result = [dict([('id', a)]+[('results', {i['result']:i['count'] for i in b})]) for a, b in new_result]

:

[{'id': 1, 'results': {'failed': 20, 'passed': 10}}, {'id': 2, 'results': {'failed': 100}}]
+1

collections.defaultdict, + groupby.

from collections import defaultdict

d = defaultdict(lambda: defaultdict(int))

for i in LD:
    d[i['id']][i['result']] += i['count']

res = [{'id': k, 'result': dict(v)} for k, v in d.items()]

# [{'id': 1, 'result': {'failed': 20, 'passed': 10}},
#  {'id': 2, 'result': {'failed': 100}}]
+1

Source: https://habr.com/ru/post/1694929/


All Articles