我有4个项目。如何添加字典中的字典
item['bigCtgr'] = 'item'
item['smaCtgr'] = 'food'
item['ssCtgr'] = 'apple'
item['sCtgr'] = 'red'
我将多次添加到process_item。 所以我想让这样的结构。 喜欢的东西
{"item" :
{"food":
{"apple":
{"green":NULL},
{"red":NULL}},
{"banana":
{"yellow":NULL},
{"green":NULL}},
}
{"sweet":
{"candy":
{"yellow":NULL}}
}
}
类别,但我的代码不能正常工作,我不知道为什么。
class CategoryPipeline(object):
global ctgr
ctgr = {}
def __init__(self):
global file
file = open("test.json","w")
def process_item(self, item, spider):
if item['bigCtgr'] not in ctgr.keys():
ctgr[item['bigCtgr']] = {item['smaCtgr']: {item['ssCtgr'] : {item['sCtgr'] : 'NULL'}}}
if item['smaCtgr'] not in ctgr[item['bigCtgr']].keys():
ctgr[item['bigCtgr']][item['smaCtgr']] = {item['ssCtgr']: {item['sCtgr'] : 'NULL'}}
elif item['ssCtgr'] not in ctgr[item['bigCtgr']][item['smaCtgr']].keys():
ctgr[item['bigCtgr']][item['smaCtgr']][item['ssCtgr']] = {item['sCtgr'] : 'NULL'}
else:
ctgr[item['bigCtgr']][item['smaCtgr']][item['ssCtgr']][item['sCtgr']] = 'NULL'
def __del__(self):
b = json.dumps(ctgr, ensure_ascii=False).encode('utf-8')
file.write(b)
file.write('\n')
file.close()
我该如何编码?
不太清楚,你想的瓦莱斯为'NULL','bigCtgr'的意义是什么等 –
我只想使用仅字典的层次结构.. – Amily
你可以把它作为样本输入和期望的输出,所以我可以更好地测试它和t ry给你一个答案 –