Home > Software engineering >  Python Iterating and Creating a Nested Dictionary
Python Iterating and Creating a Nested Dictionary

Time:10-10

I have some data that is in the below format (mylist) and I am trying to convert it into a nested dictionary but struggling to get the format correct. I've tried several variations of iterations and transformations but can't get the desired result. Can I get some help getting the data in desired format as shown in the desired result using the data format in mylist?

mylist = [
    [('floor', 'first_floor'), ('bed_room', 'room1'), ('windows', 2), ('color', 'violet')],
    [('floor', 'second_floor'), ('bed_room', 'room2'), ('windows', 4), ('color', 'violet')],
]

nest_keys = ['floor', 'bedroom']
cmd_tree = {}
for i in mylist:
    last_element = True
    for key in reversed(nest_keys):
        if last_element is True:
            cmd_tree = {key: dict([x for x in i if x[0] not in nest_keys])}
            last_element = False
        else:
            cmd_tree = {key: cmd_tree}

print(cmd_tree)

Current Result:

{'floor': {'bedroom': {'bed_room': 'room2', 'windows': 4, 'color': 'violet'}}}

Desired Result:

{'floor': {'first_floor': {'bed_room': {'room1': {'color': 'white',
                                                  'windows': 2}}},
           'second_floor': {'bed_room': {'room2': {'color': 'violet',
                                                   'windows': 4}}}}}

CodePudding user response:

No need to loop in reverse, loop through the list and each initial iteration is a floor, then loop through it's contents to create the floors details:

result = {}
br = 'bed_room'

for (_, floor_name), *details in mylist:
    result[floor_name] = {br: {}}
    
    for name, detail in details:
        if name == br:
            room = detail
            result[floor_name][br][room] = {}
        else:
            result[floor_name][br][room][name] = detail

print({'floor': result})

{'floor': {'first_floor': {'bed_room': {'room1': {'color': 'violet',
                                                  'windows': 2}}},
           'second_floor': {'bed_room': {'room2': {'color': 'violet',
                                                   'windows': 4}}}}}
  • Related