[英]how can I add dictionaries in dictionary
I have 4 items. 我有四个项目。
item['bigCtgr'] = 'item'
item['smaCtgr'] = 'food'
item['ssCtgr'] = 'apple'
item['sCtgr'] = 'red'
and i will add to process_item many times. 我会多次添加到process_item中。 so i want to make structure like this. 所以我想做这样的结构。 Something like category 像类别
{"item" :
{"food":
{"apple":
{"green":NULL},
{"red":NULL}},
{"banana":
{"yellow":NULL},
{"green":NULL}},
}
{"sweet":
{"candy":
{"yellow":NULL}}
}
}
but my code is not working and I don't know why. 但我的代码无法正常工作,我也不知道为什么。
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()
How can i make the code? 我该如何制作代码?
I implemented a tree with dict and __missing__
function. 我用dict和__missing__
函数实现了一棵树。 This adds nodes if it does not exist 如果不存在,则会添加节点
import json
class CategoryNode(dict):
def __missing__(self,key):
self[key] = CategoryNode()
return self[key]
def add_item(self, item):
self[item['bigCtgr']][item['smaCtgr']][item['ssCtgr']][item['sCtgr']] = CategoryNode()
class CategoryPipeline(object):
ctgr = CategoryNode()
file = "test.json"
def process_item(self, item, spider):
CategoryPipeline.ctgr.add_item(item)
def json(self):
json.dump(CategoryPipeline.ctgr,open(CategoryPipeline.file,'w'), ensure_ascii=False, encoding='utf-8')
This is how you may use it 这是您可能会使用的方式
cp = CategoryPipeline()
item = {}
item['bigCtgr'] = 'item'
item['smaCtgr'] = 'food'
item['ssCtgr'] = 'apple'
item['sCtgr'] = 'red'
item2 = {}
item2['bigCtgr'] = 'item'
item2['smaCtgr'] = 'food'
item2['ssCtgr'] = 'Orange'
item2['sCtgr'] = 'orange'
cp.process_item(item,"Yo")
cp.process_item(item2,"Yo")
cp.json()
and also i found this function 我也发现了这个功能
class CategoryPipeline(object):
global inf_dict, ctgr
inf_dict = lambda: collections.defaultdict(inf_dict)
ctgr = inf_dict()
def __init__(self):
global file
file = open("test.json","w")
def process_item(self, item, spider):
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.