我正在尝试使用for循环创建嵌套的json,Json值是Dynamic,子代的长度可以变化,没有固定的长度,结构也应该是
BuildingGroup
Building1
Ward
Room
Bed
Ward
Ward
Room
Bed
Bed
BuildingGroup始终是根节点,但是子代可能会有所不同,我需要使用参数动态添加子代。这就是我到目前为止所拥有的。
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()应该创建一个名为'Ward1'
的病房,并将10个Rooms
添加到Ward1
输出。
{'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})})})})
第一次迭代有效,但是在第一次迭代之后,我得到了这个错误。
TypeError: 'int' object does not support item assignment
答案 0 :(得分:2)
我调试了您的代码,这有点奇怪,但是我解决了。您的代码目前仅适用于一个Ward
,我已经编写了自己的版本,向您展示了针对多个病房进行此操作的方法。
我评论了您的代码以向您显示主要更改。
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)
现在这是我的版本:
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)