Transform list of dict (with 2 keys/values) in a single dict where values of first key is the key of the second value

Viewed 28

I want to make aggregations and use annotate with Count (group by). But I would like to transform my result as below

mygroupby = Mymodel.objects.all().values('field1').annotate(total=Count('field1'))
result = [wound_stat for wound_stat in wound_stats]

currently result

[
    {'field1': 'A', 'total': 1}, 
    {'field1': 'B', 'total': 4}, 
    {'field1': 'C', 'total': 2}, 
    {'field1': 'D', 'total': 2}, 
    {'field1': 'E', 'total': 2}
]

expected result

{'A': 1, 'B': 4, 'C': 2, 'D': 2, 'E': 2}

what is the best way? regards

1 Answers

I would use values_list to get list of tuples:

mygroupby = Mymodel.objects.all().annotate(total=Count('field1')).values_list('field1', "total")

and do final transformation in python:

result = {i[0]:i[1] for i in mygroupby}

it's probably suboptimal, but simple enough to figure out what's happening

Related