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}
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.
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.
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