nested dictionary python

2019-04-02 16:01发布

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条回答
Deceive 欺骗
2楼-- · 2019-04-02 16:13

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.

查看更多
劫难
3楼-- · 2019-04-02 16:17

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
查看更多
混吃等死
4楼-- · 2019-04-02 16:20

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.

查看更多
登录 后发表回答