Reputation: 35
I am stuck in creating nested dictionary from Django QuerySet My code is
qr_dict = [{'id':i.pop('ID'), 'data':[{i['ACCOUNT_NAME']}] } for i in query_result]
i got the result from code listed above:
[{'id': 123, 'data': [{'MUHAMMAD ADNAN'}]}, {'id': 123, 'data': [{'NAVEED AHMED SUNNY'}]}]
i need the result like following dictionary list:
[{'id': 123, 'data': [{'MUHAMMAD ADNAN'},{'NAVEED AHMED SUNNY'}]}]
what is wrong i am doing please help thanks in advance.
Upvotes: 1
Views: 210
Reputation: 17322
you can use collections.defaultdict:
from collections import defaultdict
result = defaultdict(list)
for d in query_result:
result[d['ID']].append(d['ACCOUNT_NAME'])
qr_dict = [{'id': k, 'data': [{e} for e in v]} for k, v in result.items()]
Upvotes: 0
Reputation: 82785
Using dict.setdefault
Ex:
result = {}
for i in query_result:
result.setdefault(i['ID'], []).append(i['ACCOUNT_NAME'])
Upvotes: 1