How do i convert the list of dicts having common key value pair to a new dict with keys as the common value?

Question:

I have this list having multiple dictionaries, but each dictionary has a common key through which I want to create a new Dictionary like below
list = [{"local_id":1,"id":29,"name":"Ashish"},{"local_id":2,"id":29,"name":"Boora"},{"local_id":3,"id":30,"name":"Harshdeep"},{"local_id":4,"id":30,"name":"Singh"},{"local_id":5,"id":31,"name":"Deepak"}  ]

This is the desired result
dictionry = { 29:{'details':[{"local_id":1,"id":29,"name":"Ashish"},{"local_id":2,"id":29,"name":"Boora"}]}, 30:{'details':[{"local_id":3,"id":30,"name":"Harshdeep"},{"local_id":4,"id":30,"name":"Singh"}]}, 31:{'details':[{"local_id":5,"id":31,"name":"Deepak"}]} }

Asked By: Ashish Boora

||

Answers:

Use setdefault and create the output dictionary

result = {}
for item in list:
    result.setdefault(item["id"], {}).setdefault("details", []).append(item)
print(result)
Answered By: Albin Paul
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.