Python - 嵌套字典中的反转
给定一个嵌套字典,执行键的反转,即最内层嵌套变为最外层,反之亦然。
Input : test_dict = {“a” : {“b” : {}},
“d” : {“e” : {}},
“f” : {“g” : {}}
Output : {‘b’: {‘a’: {}}, ‘e’: {‘d’: {}}, ‘g’: {‘f’: {}}
Explanation : Nested dictionaries inverted as outer dictionary keys and viz-a-vis.
Input : test_dict = {“a” : {“b” : { “c” : {}}}}
Output : {‘c’: {‘b’: {‘a’: {}}}}
Explanation : Just a single key, mapping inverted till depth.
方法:使用循环+递归
这是可以执行此任务的粗暴方式。在此,我们使用递归提取每个键从外部到内部的所有路径,然后使用它来反转结果中的排序。
Python3
# Python3 code to demonstrate working of
# Inversion in nested dictionary
# Using loop + recursion
# utility function to get all paths till end
def extract_path(test_dict, path_way):
if not test_dict:
return [path_way]
temp = []
for key in test_dict:
temp.extend(extract_path(test_dict[key], path_way + [key]))
return temp
# function to compute inversion
def hlper_fnc(test_dict):
all_paths = extract_path(test_dict, [])
res = {}
for path in all_paths:
front = res
for ele in path[::-1]:
if ele not in front :
front[ele] = {}
front = front[ele]
return res
# initializing dictionary
test_dict = {"a" : {"b" : {"c" : {}}},
"d" : {"e" : {}},
"f" : {"g" : {"h" : {}}}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# calling helper function for task
res = hlper_fnc(test_dict)
# printing result
print("The inverted dictionary : " + str(res))
输出
The original dictionary is : {'a': {'b': {'c': {}}}, 'd': {'e': {}}, 'f': {'g': {'h': {}}}}
The inverted dictionary : {'c': {'b': {'a': {}}}, 'e': {'d': {}}, 'h': {'g': {'f': {}}}}