反转未知深度的嵌套字典

2024-10-03 06:23:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我想买一本这样的字典:

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

看起来像这样:

^{2}$

词典嵌套到未知深度。这无疑是在测试我的递归知识。在

到目前为止我有这个。我觉得这很管用。然而,我想知道是否有一种更像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

Tags: inforif字典foodef方式update
1条回答
网友
1楼 · 发布于 2024-10-03 06:23:15

您可以跟踪已看到的关键点:

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'}}}}))

输出:

^{pr2}$

但是,只有当每个字典只有一个键时,上述解决方案才有效。要一般地查找所有路径,请使用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]}]

相关问题 更多 >