反转深度未知的嵌套字典

时间:2018-10-12 21:12:13

标签: python dictionary recursion

我正在尝试获得一个像这样的字典:

{1:{2:{3:{4:'foo'}}}}

看起来像这样:

'foo': [1,2,3,4]

字典被嵌套到未知深度。这肯定在测试我的递归知识。

到目前为止,我有这个。我认为这可行。但是,我想知道是否还有一种更Python化的方式来做到这一点:

def denest(nested_dict):
    denested_dict = {}
    for k, v in nested_dict.items():
        if isinstance(v, dict):
            sub_dict = denest(v)
            for t, s in sub_dict.items():
                sub_dict[t] +=[k]
            denested_dict.update(sub_dict)
        else:
            denested_dict[v] = [k]

    return denested_dict

1 个答案:

答案 0 :(得分:4)

您可以跟踪已看到的键:

def build_new(_d, seen = []):
  [[a, b]] = _d.items()
  return {b:seen+[a]} if not isinstance(b, dict) else build_new(b, seen+[a])

print(build_new({1:{2:{3:{4:'foo'}}}}))

输出:

{'foo': [1, 2, 3, 4]}

但是,上述解决方案仅在每个词典只有一个键时才有效。要一般地查找所有路径,请使用yield

def all_paths(d, seen = []):
  for a, b in d.items():
    if not isinstance(b, dict):
      yield {b:seen+[a]}
    else:
      yield from all_paths(b, seen+[a])

d = {1:{2:{3:'bar', 4:'foo', 5:{6:'stuff'}}}}
print(list(all_paths(d)))

输出:

[{'bar': [1, 2, 3]}, {'foo': [1, 2, 4]}, {'stuff': [1, 2, 5, 6]}]
相关问题