python 如何将具有公共键值对的字典列表转换为一个新的字典,并将键作为公共值?

nhn9ugyo  于 2023-01-08  发布在  Python
关注(0)|答案(1)|浏览(164)

我有一个包含多个字典的列表,但每个字典都有一个公共键,我想通过它创建一个新字典,如下所示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"}  ]
这是所需的结果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"}]} }

njthzxwz

njthzxwz1#

使用setdefault并创建输出字典

result = {}
for item in list:
    result.setdefault(item["id"], {}).setdefault("details", []).append(item)
print(result)

相关问题