我的`词典`在Python

时间:2017-09-03 02:58:41

标签: python python-2.7 python-3.x dictionary

我有一个名为add_item(self, item)的方法,其中我想用更多项目更新items_category

def add_item(self, item):

            self.items.update({item.category: {item.name: item}})
            """
            IN My Tests.
            self.nakkumart.add_item(Item("Call Of Duty", "Game", 3500, 1))
            self.nakkumart.add_item(Item("God Of War 3", "Game", 3500, 1))
            print(self.nakkumart.items['Game']['Call Of Duty'].price) >>>Raises KeyError 'Call Of Duty Not found'
            """ 

我认为每次调用add_item(Item)时,item.category都会重新创建,并且之前的值已丢失。这是我实现self.items.update({item.category: {item.name: item}})的方式,或者我该怎么做才能print(len(self.nakkumart.items['Game']))在连续调用add_item(Item)时打印2

1 个答案:

答案 0 :(得分:1)

您只是更新高级词典而不是内层词典。

def add_item(self, item):
    self.items.update({item.category: {item.name: item}})

这表示将'Game'键的值替换为{item.name: item}的新词典,该词典会抛出任何其他值。

您需要首先获取内部字典,更新它,然后更新外部字典。

def add_item(self, item):
    cat_dict = self.items.get(item.category, {})
    cat_dict.update(item.name=item)
    self.items.update(item.category=cat_dict)