在公共密钥中合并具有相同值的多个字典列表 [英] Merge multiple list of dict with same value in common key

查看:50
本文介绍了在公共密钥中合并具有相同值的多个字典列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有4份字典

list1 = [{'a':0,'b':23}, {'a':3,'b':77},{'a':1,'b':99}]

list2 = [{'a':1,'c':666},{'a':4,'c':546}]

list3 = [{'d':33,'a':3},{'d':1111,'a':4},{'d':76,'a':1},{'d':775,'a':0}]

list4 = [{'a':2,'e':12},{'a':4,'e':76}]

列表中的每个字典都有一个公用键"a".我的要求是应合并所有列表中dict中具有相同值的"a"键,如果合并时dict中不存在特定键,则为这些键分配0或忽略这些键.例如对于具有值1的键"a",在上面的示例中,我们有2个字典,一个来自list1,即{'a':0,'b':23},一个是list3,最后一个字典,即{'d':775,a':0},因此我们首先确定了具有相同'a'值的字典,现在需要合并这些字典即{'a':0,'b':23,'c':0,'d':775,'e':0},因为两个字典都没有'c',所以分配了'c'此处为0

Every dict in the list has a common key 'a'. My requirement is 'a' key with same value in dict from all the list should be merged and if a particular key does not exist in the dicts while merging, then assign 0 for those keys or just omit those keys. for eg. for key 'a' with value 1, from above example we have 2 dicts, one from list1 i.e {'a':0,'b':23} and one is list3, last dict i.e {'d':775,'a':0}, so 1st we have identified the dicts with same 'a' value, now need to merge these dicts i.e {'a':0, 'b':23, 'c':0, 'd':775, 'e':0}, since both the dict didn't have 'c', 'c' is assigned as 0 here

我的输出应为:

[{'a':0,'b':23,'c':0,'d':775, 'e':0},{'a':1,'b':99,'c':666,'d':76,'e':0},{'a':2,'b':0,'c':0,'d':0,'e':12},{'a':3,'b':77,'c':0,'d':33,'e':0}, {'a':4,'b':0,'c':546,'d':1111,'e':76}]

使用最小循环或列表理解

usings minimum loops or list comprehension

推荐答案

如果您想使用更Python化的方式:

If you want a more pythonic way:

from itertools import groupby
from pprint import pprint
from collections import ChainMap

a = [{'a':0,'b':23}, {'a':3,'b':77}, {'a':1,'b':99}]
b = [{'a':1,'c':666}, {'a':4,'c':546}]
c = [{'d':33,'a':3}, {'d':1111,'a':4}, {'d':76,'a':1}, {'d':775,'a':0}]
d = [{'a':2,'e':12}, {'a':4,'e':76}]

dict_list = a + b + c + d

# You just need to specify the key you want to use in the lambda function
# There's no need to declare the different key values previously
res = map(lambda dict_tuple: dict(ChainMap(*dict_tuple[1])),
          groupby(sorted(dict_list,
                         key=lambda sub_dict: sub_dict["a"]),
                  key=lambda sub_dict: sub_dict["a"]))

pprint(list(res))

输出:

[{'a': 0, 'b': 23, 'd': 775},
 {'a': 1, 'b': 99, 'c': 666, 'd': 76},
 {'a': 2, 'e': 12},
 {'a': 3, 'b': 77, 'd': 33},
 {'a': 4, 'c': 546, 'd': 1111, 'e': 76}]

编辑(改进):

您也可以使用

from _operator import itemgetter
key=itemgetter("a")

代替

key=lambda sub_dict: sub_dict["a"]

带有itemgetter的版本要快得多.使用您提供的示例:

The version with itemgetter is much faster. Using the example you provided:

- Lambda: 0.037109375ms
- Itemgetter: 0.009033203125ms

这篇关于在公共密钥中合并具有相同值的多个字典列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆