gpt4 book ai didi

python - 如何在字典中添加字典

转载 作者:行者123 更新时间:2023-12-01 03:23:07 28 4
gpt4 key购买 nike

我有 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()

如何编写代码?

最佳答案

我用 dict 和 __missing__ 实现了一棵树功能。如果节点不存在,则添加节点

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')

这就是你可以如何使用它

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()

关于python - 如何在字典中添加字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41735212/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com