1

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

3
  • 1
    Do you want {Category_id: {Product_id:... productInstance}{prod_id_1: this instance}} (with a colon after Category_id)? Commented Nov 9, 2011 at 23:16
  • oh yeah.. sorry my bad.. i will edit the desc.. Commented Nov 9, 2011 at 23:18
  • Please, show us a valid Python example of what you want the dictionary to look like. Do you mean {1: {2: productInstance, 3: productInstance2, ...}, 4: {...}} where 1 and 4 are category ids and 2 and 3 are product ids? Commented Nov 9, 2011 at 23:18

3 Answers 3

7

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.