【问题标题】:How to combine multiple nested dictionaries into one如何将多个嵌套字典合并为一个
【发布时间】:2019-04-02 00:43:29
【问题描述】:

如果我有 n 个具有不同深度的嵌套字典,其中最深的嵌套字典的值作为列表,

例如:

{"a":{"b": {"c": {"d": ["ab"]}}}},
{"a" : {"b": {"d": ["aa"]}}}, 
{"a": {"f":{"c":["xx"]}}}, 
{"a":{"b": {"c": {"d": ["ef"]}}}}

我怎样才能将这些组合在一起得到

{"a": {"b": {"c": {"d": ["ab","ef"]}}, "d": ["aa"]}, "f":{"c":["xx"]}}}

这可以被认为是一棵树,其中"a" 是整个树的父级,"b""f" 是子树等等。

我尝试使用递归,但实际上我不知道从哪里开始

【问题讨论】:

  • 到目前为止您尝试过什么?请发布您的尝试

标签: python dictionary recursion nested


【解决方案1】:

你可以使用递归itertools.groupby:

from itertools import groupby
data = [{"a":{"b": {"c": {"d": ["ab"]}}}}, {"a" : {"b": {"d": ["aa"]}}}, {"a": {"f":{"c":["xx"]}}}, {"a":{"b": {"c": {"d": ["ef"]}}}}]
def group(d):
  if all(not isinstance(i, dict) for i in d):
    return [i for b in d for i in b]
  r = [i for b in d for i in b.items()]
  _d = [[a, [c for _, c in b]] for a, b in groupby(sorted(r, key=lambda x:x[0]), key=lambda x:x[0])]
  return {a:b[0] if len(b) == 1 else group(b) for a, b in _d}

print(group(data)) 

输出:

{'a': {'b': {'c': {'d': ['ab', 'ef']}, 'd': ['aa']}, 'f': {'c': ['xx']}}}

【讨论】:

    【解决方案2】:

    由于您的每个 dicts 仅包含一个键,因此您实际上不需要递归。迭代地获取下一个内部字典会更有效,直到你得到一个列表,此时你用列表扩展子列表:

    l = [
        {"a": {"b": {"c": {"d": ["ab"]}}}},
        {"a": {"b": {"d": ["aa"]}}},
        {"a": {"f": {"c": ["xx"]}}},
        {"a": {"b": {"c": {"d": ["ef"]}}}}
    ]
    o = {}
    for d in l:
        n = o
        m = d
        p = None
        while isinstance(m, dict):
            if p is not None:
                if k not in p:
                    p[k] = {}
                n = p[k]
            (k, m), = m.items()
            p = n
        p.setdefault(k, []).extend(m)
    

    o 变为:

    {'a': {'b': {'c': {'d': ['ab', 'ef']}, 'd': ['aa']}, 'f': {'c': ['xx']}}}
    

    【讨论】:

      猜你喜欢
      • 2021-01-31
      • 2012-02-10
      • 1970-01-01
      • 2020-07-29
      • 1970-01-01
      • 2020-01-14
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多