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"}]} }
Answers:
Use setdefault and create the output dictionary
result = {}
for item in list:
result.setdefault(item["id"], {}).setdefault("details", []).append(item)
print(result)
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"}]} }
Use setdefault and create the output dictionary
result = {}
for item in list:
result.setdefault(item["id"], {}).setdefault("details", []).append(item)
print(result)