我有一个 list
由 dict
组成结构相同,
sample = [{'a':1, 'b':2, 'c':3}, {'a':1, 'b':2, 'c':4}, {'a':2, 'b':2, 'c':5}, {'a':2, 'b':3, 'c':5}]
我想通过键将它们组合起来 a
,输出应该是[{'a': 1, 'd': [{'b':2, 'c':3}, {'b':2, 'c':4}]}, {'a': 2, 'd': [{'b':2, 'c':5}, {'b': 3, 'c':5}]}]
最佳答案
您可以使用 itertools.groupby
:
>>> from itertools import groupby
>>> result = []
>>> for key, group in groupby(sorted(sample, key=lambda x:x['a']), key=lambda x:x.pop('a')):
result.append({'a':key, 'd':[*group]})
>>> result
[{'a': 1, 'd': [{'b': 2, 'c': 3}, {'b': 2, 'c': 4}]},
{'a': 2, 'd': [{'b': 2, 'c': 5}, {'b': 3, 'c': 5}]}]
注意:您不需要 sorted
如果保证字典列表按键 a
的值排序.
关于python - 按某个键合并字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63192002/