How do I create a nested dictionary in python So, I want the data be in this form..
{Category_id: {Product_id:... productInstance},{prod_id_1: this instance}}
Basically if i do something like this lets say I want to check whether the
product_id = 5 is in category 1.
so if I do
Dict[1].has_key(5)--> be true or false..
My bad code is
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}}
THanks
Check my NestedDict class here: https://stackoverflow.com/a/16296144/2334951
I hope that with some intuition this example covers the question.
I think this is closer to what you want:
Dicts in python are basically always a "collection" of "items"; each "item" is a key and a value, separated by a colon, and each item is separated by the next with a comma. An item cannot have more than one key or value, but you can have collections as keys or values.
Looking at your second example:
the outer dict needs another comma, between the end of the first item (with key
1
) and second (with key2
).Additionally, it's not quite clear what
this instance
is meant to mean, but it is often the case that methods on objects are passed the object itself as first parameter, and by convention, that's calledself
, but can be given any name (and this is sometimes done to reduce confusion, such as with metaclasses)Finally; bare words,
p_id
and so forth, are rarely valid unless they are a variable name (assigned to earlier) or an attribute of another object (possiblyself.p_id
). I don't know if that's the problem you're having.