gpt4 book ai didi

python - 嵌套字典 python

转载 作者:太空宇宙 更新时间:2023-11-04 07:11:34 25 4
gpt4 key购买 nike

如何在 python 中创建嵌套字典所以,我希望数据采用这种形式..

{Category_id: {Product_id:... productInstance},{prod_id_1: this instance}}

基本上如果我做这样的事情假设我想检查

product_id = 5 is in category 1.

如果我这样做

Dict[1].has_key(5)--> be true or false..

我的错误代码是

fin = readFile(db)
categoryDict = defaultdict(list)
itemDict ={}
for line in fin:
itemInstance = setItemInstances(line)

itemDict[itemInstance._product_id] = itemInstance
categoryDict[itemInstance._category_id].append(itemDict)




EDIT: example
dict = {1: { p_id: p_instance_1,
p_id_2: p_ins_2}
2:{ p_in_this_cat_id: this isntance}}

谢谢

最佳答案

我认为这更接近你想要的:

fin = readFile(db)
categoryDict = defaultdict(dict) # automatically create a subdict
for line in fin:
itemDict = {} # a new innermost dict for every item
itemInstance = setItemInstances(line)
itemDict[itemInstance._product_id] = itemInstance
categoryDict[itemInstance._category_id] = itemDict

关于python - 嵌套字典 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8073071/

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