0

I am trying to create a nested json using for loops, The Json values are Dynamic and the length of the children can vary there is no fixed length, Also the structure should be

BuildingGroup
  Building1
   Ward
    Room
     Bed
   Ward
   Ward
     Room
       Bed
       Bed

The BuildingGroup is the Root Node always, but the children may vary I need to add children dynamically using paramaters. This is what i have so far.

import collections
def add_element(root, path, data):
    if len(path) == 1:
        root[path[0]] = data
    else:
        add_element(root[path[0]], path[1:], data)


def create_tree(Wards,WardName,Rooms):
    count = 1
    ward_list=[]    
    room_list= []
    tree = lambda: collections.defaultdict(tree)
    root = tree()
    path_list= ['BuildingGroup', 'Building1']
    for i in range(1,Wards):
        Ward = 'Ward' + str(count)
        path_list,append(Ward)
        ward_list.append(Ward)
        print (ward_list)
        print (path_list)
        count += 1
        add_element(root,path_list, 1 )
    path_list.append(WardName)
    for i in range(1, Rooms):
        Room = 'Room' + str(count)
        path_list.append(Room)

        room_list.append(Room)
        print (root)
        add_element(root,path_list, 1 )

create_tree(1, 'Ward1', 10)

Create_tree() should create one Ward Named 'Ward1' and add 10 Rooms to Ward1

Ouput.

{'BuildingGroup': defaultdict(<function create_tree.<locals>.<lambda> at 0x000002054A7AE510>, {'Building1': defaultdict(<function create_tree.<locals>.<lambda> at 0x000002054A7AE510>, {'Ward1': defaultdict(<function create_tree.<locals>.<lambda> at 0x000002054A7AE510>, {'Room1': 1})})})})

The first iteration Works but after the first iteration I am getting this error.

TypeError: 'int' object does not support item assignment

1 Answer 1

2

I debugged your code, it was kind of strange but I worked it out. Your code only works for one Ward at the moment, I've written my own version to show you a way to do this for multiple wards.

I commented your code to show you the major changes.

import collections
def add_element(root, path, data):
    if len(path) == 1:
        root[path[0]] = data
    else:
        add_element(root[path[0]], path[1:], data)


def create_tree(Wards,WardName,Rooms):
    count = 1
    ward_list=[]
    room_list= []
    tree = lambda: collections.defaultdict(tree)
    root = tree()
    path_list= ['BuildingGroup', 'Building1']
    for i in range(1,Wards):
        Ward = 'Ward' + str(count)
        # Check your typos, this line had a ',' in it instead of a '.'
        path_list.append(Ward)
        ward_list.append(Ward)
        print (ward_list)
        print (path_list)
        count += 1
        add_element(root,path_list, 1 )
    path_list.append(WardName)
    for i in range(1, Rooms):
        # Initialise room_list with the path_list from the ward
        room_list = path_list.copy()
        # We have a new variable, 'i' for counting rooms, so don't use 'count' here as it never changes
        Room = 'Room' + str(i)
        # path_list.append(Room) - No! Bad! Don't change the path_list, this is the same for each room
        room_list.append(Room)
        # Use the room_list here instead of the path_list
        add_element(root,room_list, 1 )
        print(root)

my_tree = create_tree(1, 'Ward1', 10)

Now here's my version:

import json


def create_tree(ward_list, number_of_rooms):
    tree = {'BuildingGroup': {'Building1': {}}}
    for ward in ward_list:
        tree['BuildingGroup']['Building1'][ward] = []
        for i in range(1, number_of_rooms + 1):
            tree['BuildingGroup']['Building1'][ward].append("Room" + str(i))
    return tree


wards = ['Ward1', 'Ward2']
my_tree = create_tree(wards, 10)
tree_json = json.dumps(my_tree)
print(tree_json)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.