Help

3

How to make tree of dictionary?

Avatar
Kamlesh Vadhiya

My input is 

input_dic = {

1: [2,3], 

2: [10],

3: [4], 

4: [],

5:[6,7] ,

6: [], 

7: [8], 

8: [9], 

9: [10], 

10: []

}


i want output as follows 

output = {1 : { 2 : {10 : { } },3 : {4: { } }, 5 : { 6 : { }, 7 : { 8 : { 9 : { } } } } }}

Avatar
Discard
1 Answer
1
Best Answer

Hi!

The code below is an example, adapt it as you need.

input_dict = {1: [2, 3], 2: [10], 3: [4], 4: [], 5: [6, 7], 6: [], 7: [8], 8: [9], 9: [10], 10: []}

def get_values(number):
result = {}
current_values = input_dict[number]
if current_values.__len__() >= 1:
for current_value in current_values:
if input_dict[current_value].__len__() >= 1:
result[current_value] = dict.fromkeys(input_dict[current_value],
get_values(input_dict[current_value][0]) or {})

return result

values = {}
for i in range(1, input_dict.__len__()):
if input_dict[i].__len__() > 1:
values[i] = get_values(i)

Best regards!

Avatar
Discard