如何在字典中添加字典

2024-09-30 05:19:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有4样东西。你知道吗

item['bigCtgr'] = 'item'
item['smaCtgr'] = 'food'
item['ssCtgr'] = 'apple'
item['sCtgr'] = 'red'

我会多次添加到这个项目中。 所以我想做这样的结构。 类似于分类

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

我该怎么做代码?你知道吗


Tags: inselfapplefooddefnotkeysitem
2条回答

我还发现了这个函数

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

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

相关问题 更多 >

    热门问题