简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM