简体   繁体   English

如何将具有公共键值对的字典列表转换为以键为公共值的新字典?

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

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

Usesetdefault and create the output dictionary使用setdefault并创建 output 字典

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在一个dicts列表中获得具有公共密钥最大值的整个dict - How to get whole dict with max value of a common key in a list of dicts 查找公用密钥:字典中的值对,用于不可哈希的密钥和值 - Find common key: value pair in dict for non hashable keys and values 在字典列表中查找公用键值对的pythonic方法 - pythonic way to find common key value pair among list of dict 如何在字典列表中找到公用键并按值对它们进行排序? - How to find common keys in a list of dicts and sort them by value? 在 List of Dicts 中,找到常用 Dict 字段的 min() 值 - In List of Dicts, find min() value of a common Dict field 如何将字典/嵌套字典的字典转换为列表字典 - How do I convert dict of dicts/nested dicts into dict of list 如何将新的键值对添加到字典列表中的现有键值对中? - How to add a new key value pair to existing key value pair from list of dicts? 如果键已包含在字典中,如何以智能方式将新的键值对添加到字典中? - How do I add a new key-value pair in a smart way to a dict if the key is already contained in the dict? 如何从具有嵌套字典列表的字典中提取特定键值对 - how to extract a specific key value pair from a dict with a nested list of dicts 从具有 2 个公共键的字典列表中构建新字典的最有效方法? - Most efficient way to build a new dict from a list of dicts with 2 common keys?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM