嵌套合并dicts

时间:2018-06-07 22:28:31

标签: python dictionary

我有多个词典:

a = {
   "project_1": {
       "roles": ["role1"]
   },
   "project_4": ["foo"]
}

b = {
   "project_1": {
       "roles": ["role2"]
   },
   "project_2": {
       "roles": ["role4"]
   }
}
c = {
    "project_5": {
        "roles": ["role5"]
   }
}

如何合并这些词典以获得以下内容:

d = {
    "project_1": {
         "roles": ["role1","role2"]
    },
    "project_2": {
         "roles": ["role4"]
    },
    "project_4": ["foo"],
    "project_5": {
         "roles": ["role5"]
    }
}

关于合并字典的其他问题,我看到答案要么以预定方式覆盖值,要么依赖唯一键,要么用于fixed number of dictionaries。我需要为2个或更多字典保留类似键的嵌套值。

我的问题的限制是:

  • 每个字典有一个可变数量的键(" project_X")
  • dicts不是固定深度但具有最大深度

1 个答案:

答案 0 :(得分:2)

您可以将itertools.groupby与递归一起使用:

import itertools
def group(_input):
  d = list(itertools.chain(*list(map(lambda x:list(x.items()), _input))))      
  _s = [[a, [c for _, c in b]] for a, b in itertools.groupby(sorted(d, key=lambda x:x[0]), key=lambda x:x[0])]
  return {a:group(b) if all(isinstance(i, dict) for i in b) else list(itertools.chain(*b)) for a, b in _s}

print(group([a, b, c]))

输出:

{'project_1': {'roles': ['role1', 'role2']}, 'project_2': {'roles': ['role4']}, 'project_4': ['foo'], 'project_5': {'roles': ['role5']}}