我如何在 python 中创建嵌套字典的字符串(无循环)作为其相应树的一系列分支

How can i create a string of a nested dictionary(no loops) as a series of branches of its corresponding tree in python

问题:

打印字典的函数,如下例所示

recursive_dict = {

   'a': 1,
   'b': {
       'c': 1,
       'd': 4
   },
   'e':
   {
       'f': 3,
       'g':
       {
           'h': 5,
           'i': 6
       }
   },
   'j': 10
}
to
'a' - 1
'b' - 'c' - 1
'b' - 'd' - 4
'e' - 'f' - 3
'e' - 'g' - 'h' - 5
'e' - 'g' - 'i' - 6
'j' - 10

我的代码:

欢迎对代码提出任何批评,因为我是 python 初学者,或者任何使代码更易于阅读的方法。该代码在更高级别的递归值之后不起作用,因为它保留了旧密钥。我想我必须检测字典何时结束,所以我从 old_key 中删除了我连接的最后一个键。 另一个更难?想法是将字典转换为树,然后继续读取树的所有分支。

def print_dictionary_tree(tree_dict, default_separator='-', branch="", old_key=""):
    for key, value in tree_dict.items():
        if type(value) != dict:
            if old_key == "":
                branch += f"%{key}% {default_separator} {value} \n"
            else:
                branch += f"{old_key} {default_separator} /{key}/ {default_separator} {value} \n"
        else:
            if old_key != "":
                old_key += f" {default_separator} %{key}%"
            elif key != value.get(key):
                old_key += f"^{key}^"
            branch += print_dictionary_tree(value, default_separator, "", old_key)
    return branch

Returns

'a' - 1 
'b' - 'c' - 1 
'b' - 'd' - 4 
'b' - 'e' - 'f' - 3 
'b' - 'e' - 'g' - 'h' - 5 
'b' - 'e' - 'g' - 'i' - 6 
'b' - 'e' - 'j' - 10 

我找到了类似的有用链接,但我无法修复我的功能:

Loop through all nested dictionary values?

Python 生成器可以快速解决此类问题 -

def traverse(d, path = []):
  if isinstance(d, dict):
    for (k, v) in d.items():
      yield from traverse(v, [*path, k])
  else:
    yield [*path, d]

input = ...                          # <- your dict

for p in traverse(input):
  print("-".join(map(str, p)))

输出-

a-1
b-c-1
b-d-4
e-f-3
e-g-h-5
e-g-i-6
j-10

每次退出内部字典只需要清除old_keys:


def print_dictionary_tree(tree_dict, default_separator='-', branch="", old_key=""):
    for key, value in tree_dict.items():
        if type(value) != dict:
            if old_key == "":
                branch += f"{key} {default_separator} {value} \n"
            else:
                branch += f"{old_key} {default_separator} {key} {default_separator} {value} \n"
        else:
            if old_key != "":
                old_key += f" {default_separator} {key}"
            elif key != value.get(key):
                old_key += f"{key}"
            branch += print_dictionary_tree(value, default_separator, "", old_key)
            old_key = old_key.replace(key, "") ## < --- HERE
    return branch

结果:

a - 1
b - c - 1
b - d - 4
e - f - 3
e - g - h - 5
e - g - i - 6
j - 10