Reputation: 33223
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
Upvotes: 1
Views: 21482
Reputation: 4186
Check my NestedDict class here: https://stackoverflow.com/a/16296144/2334951
>>> branches = [b for b in data.paths()]
>>> ['plumbers' in k for k in branches]
[True, False, True, False, False, False]
>>> any(['plumbers' in k for k in branches])
True
>>> [k for k in branches if 'plumbers' in k]
[['new york', 'queens county', 'plumbers'], ['new jersey', 'mercer county', 'plumbers']]
>>> [data[k] for k in branches if 'plumbers' in k]
[9, 3]
I hope that with some intuition this example covers the question.
Upvotes: 1
Reputation: 156138
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:
dict = {1: { p_id: p_instance_1,
p_id_2: p_ins_2}
2:{ p_in_this_cat_id: this isntance}}
the outer dict needs another comma, between the end of the first item (with key 1
) and second (with key 2
).
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 called self
, 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 (possibly self.p_id
). I don't know if that's the problem you're having.
Upvotes: 1
Reputation: 226231
I think this is closer to what you want:
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
Upvotes: 7