python - 按某个键合并字典列表

标签 python list dictionary

我有一个 listdict 组成结构相同,

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/

相关文章:

swift - 在 Swift 中定义嵌套字典

c++ - map 和列表的迭代器显示不同的行为

Python Web 抓取 : grequests vs. 多线程请求?

python - 在列表中查找最长的不间断公共(public)元素

python - 在 "Mr."或 "Mrs."之前分割字符串

php - 如何在php页面的选项列表中显示sql行

python - 字典列表检查键 :value

python - 删除分配给字典中每个键的值列表中的重复项的函数?

python - 在 numpy 数组上运行 Tensorflow classify_image

python - 查找整数列表中所有加起来等于一个数字的数字