我是 Python 编码的初学者,希望得到您的支持。我正在编写代码来创建具有父子关系的嵌套字典。该程序以 API Rest 调用开始,在一个循环中需要提取所有子项,而新循环中的每个子项都需要提取另一个子项。我在第二个循环中遇到了一些挑战,因为每次完成递归调用时,我都会丢失我的 for 循环引用。
下面的代码示例 谢谢
def add_keys_nested_dict(dictionary, keys):
if len(keys) == 1:
dictionary.setdefault(keys[0], {})
else:
key = keys[0]
if key not in dictionary:
dictionary[key] = {}
add_keys_nested_dict(dictionary[key], keys[1:])
def getChild(data,i,dictionary,flag,child_id,depth):
#if 'attributes' in data and 'children' in data and 'name' in data['attributes'] and len(data['children'])==0:
depth=int(depth)
if depth != 0:
#for b in range(len(data['children'])):
if flag==True:
child_id=str(i)+'_child_id_'+str(f)
add_keys_nested_dict (dictionary,[child_id])
dictionary[child_id]['id']=data['id']
dictionary[child_id]['type']=data['type']
#if data['type']!='task':
tprocessanalysis=processanalysis+data['id']
try:
aresponse = requests.post(tprocessanalysis,headers=sheader)
aresponse.json()
aresponse.raise_for_status()
except requests.exceptions.HTTPError as error:
quit()
if aresponse.json()['count'] >0:
tprocessdata=aresponse.json()['elements']
if 'attributes' in tprocessdata[0] and 'name' in tprocessdata[0]['attributes'] :
dictionary[child_id]['name']=tprocessdata[0]['attributes']['name']['1033']
flag=True
if 'children' in tprocessdata[0]:
i=i+1
# the problem is that we loose the For logic when we call the function and then we restart
dictionary= dictionary[child_id]
for d in range(len(tprocessdata[0]['children'])):
child_id=str(i)+'_child_id_'+str(d)
add_keys_nested_dict (dictionary,[child_id])
dictionary[child_id]['id']=tprocessdata[0]['children'][d]['id']
dictionary[child_id]['type']=tprocessdata[0]['children'][d]['type']
flag=False
getChild(tprocessdata[0]['children'][d],i,dictionary,flag,child_id,depth-1)
#return processhouse
else:
depth=0
return processhouse
try:
response = requests.post(processanalysis,headers=sheader)
response.json()
response.raise_for_status()
except requests.exceptions.HTTPError as error:
quit()
processhouse={}
if response.json()['count'] >0:
processdata=response.json()['elements']
for a in range (len(processdata)):
types=processdata[a]['type']
processhouse[types]={}
processhouse[types]['name']=processdata[a]['attributes']['name']['1033']
if 'children' in processdata[a]:
for f in range(len(processdata[a]['children'])):
dictionary= processhouse[types]
flag=True
getChild(processdata[a]['children'][f],1,dictionary,flag,'','-1')
else:
continue
我尝试编写一个递归函数但是不起作用
your text