我有一个字典列表,如下所示:
targer = [
{"id":1,"search":"xyz"},
{"id":2,"children":[
{"id":3,"search":'xyz'},
{"id":4,"search":'xyz'},
{"id":5,"children":[
{"id":6,"search":'xyz'},
{"id":7,"search":'xyz'},
{"id":8,"search":'xyz'}]},
{"id":9,"search":'xyz'},
{"id":10,"search":'xyz'}]},
{"id":11},{"id":12}]
现在我想从目标列表中制作一个字典列表,如下所示:
output = [
{'tier1': 1, 'searchterm': 'xyz'},
{'tier1': 2, 'tier2': 3,'searchterm': 'xyz'},
{'tier1': 2,'tier2': 4,'searchterm': 'xyz'},
{'tier1': 2, 'tier2': 5,'tier3': 6,'searchterm': 'xyz'},
{'tier1': 2, 'tier2': 5,'tier3': 7,'searchterm': 'xyz'},
{'tier1': 2, 'tier2': 5,'tier3': 8, 'searchterm': 'xyz'},
{'tier1': 2, 'tier2': 9,'searchterm': 'xyz'},
{'tier1': 2, 'tier2': 10,'searchterm': 'xyz'},
{'tier1': 11, 'searchterm': 'xyz'},
{'tier1': 12, 'searchterm': 'xyz'}]
我尝试了一些步骤: 1.首先我将目标列表转换为如下列表:
mylist = [
[1, 'xyz'],
[2, 3, 'xyz'],
[2, 4, 'xyz'],
[2, 5, 6, 'xyz'],
[2, 5, 7, 'xyz'],
[2, 5, 8, 'xyz'],
[2, 9, 'xyz'],
[2, 10, 'xyz'],
[11],
[12]]
2.然后我在 mylist 上应用以下代码来获取输出:
for i in lis:
dic={}
length=len(i)
if length==2:
dic['tier1']=i[0]
dic['searchterm']=i[1]
if length==3:
dic['tier1']=i[0]
dic['tier2']=i[1]
dic['searchterm']=i[2]
if length==4:
dic['tier1']=i[0]
dic['tier2']=i[1]
dic['tier3']=i[2]
dic['searchterm']=i[3]
if length==5:
dic['tier1']=i[0]
dic['tier2']=i[1]
dic['tier3']=i[2]
dic['tier4']=i[3]
dic['searchterm']=i[4]
if length==6:
dic['tier1']=i[0]
dic['tier2']=i[1]
dic['tier3']=i[2]
dic['tier4']=i[3]
dic['tier5']=i[4]
dic['searchterm']=i[5]
target.append(dic)
但我想从直接目标列表中输出而不应用上述步骤。请帮助解决这个问题。