1.数据结构
input_dict = { 'A': { 'B': { 'C': {}, 'D': {} }, 'E': { 'F': {} } }, 'G': { 'H': {}, 'I': {} } }
2. Python 代码
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'标签:层级,1.1,递归,level,Python,dict,result,key,input From: https://www.cnblogs.com/lajf/p/17877494.html
}