我可以在这里看到许多类似的问题,但我找不到一个可以帮助我获得所需输出的问题
我有一个具有相同ID但具有不同键值对的字典列表,我想将所有这些键值对合并到一个列表条目中,下面是数据示例和所需的输出
谢谢你的帮助
data = [
{'id': '10', 'animal' : 'cat'},
{'id': '11', 'animal' : 'dog'},
{'id': '3', 'animal' : 'pigeon'},
{'id': '10', 'color' : 'yellow'},
{'id': '11', 'color' : 'brown'},
{'id': '3', 'color' : 'grey'},
{'id': '10', 'type' : 'furry'},
{'id': '11', 'type' : 'fluffy'},
{'id': '3', 'type' : 'dirty'},
]
期望输出
data = [
{'id': '10', 'animal' : 'cat', 'color' : 'yellow', 'type' : 'furry'},
{'id': '11', 'animal' : 'dog', 'color' : 'brown', 'type' : 'fluffy'},
{'id': '3', 'animal' : 'pigeon', 'color' : 'grey', 'type' : 'dirty'},
]
在Python3.9(ETA Fall 2020)中,您将能够使用
|
操作符将dict
与相同的id
键合并实现这一点有多种方法,其中之一是
defaultdict
:您可以使用
groupby
和ChainMap
来完成它groupby
处理已排序的集合,因此在调用groupby
之前对
data
进行排序ChainMap
用于将词典列表合并到单个词典中相关问题 更多 >
编程相关推荐