Python 递归输出树数据 多层级序号

1.数据结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
input_dict = {
  'A': {
    'B': {
    'C': {},
    'D': {}
  },
  'E': {
    'F': {}
  }
  },
  'G': {
    'H': {},
    'I': {}
  }
}

2. Python 代码

1
2
3
4
5
6
7
8
9
def convert_dict_to_numbers(input_dict, current_key="", level=1):
  result = {}
  for key, value in input_dict.items():
    new_key = f"{level}" if current_key == "" else f"{current_key}.{level}"
    result[new_key] = key
    if isinstance(value, dict):
      result.update(convert_dict_to_numbers(value, new_key, 1))
    level += 1
  return result

3. 输出结果

result = convert_dict_to_numbers(input_dict)

print(result)

{'1': 'A',

 '1.1': 'B',
 '1.1.1': 'C',
 '1.1.2': 'D',
 '1.2': 'E',
 '1.2.1': 'F',
 '2': 'G',
 '2.1': 'H',
 '2.2': 'I'
}

posted @   林暗惊风  阅读(48)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示