【问题标题】:My `dictionary` recreating from scratch on update in Python在 Python 中更新时从头开始重新创建我的“字典”
【发布时间】:2017-09-03 02:58:41
【问题描述】:

我有一个名为 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

【问题讨论】:

  • 如果你试试这个语句 print(self.nakkumart.items['Game']['God ​​Of War 3'].price) ,它会打印出正确的输出吗?
  • 是的,它确实打印了 3500

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


【解决方案1】:

您只是更新上层字典,而不是内部字典。

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

这表示用{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)

【讨论】:

  • @EsirKings:修改为使用另一种方式调用dict.update(key=value),而不是创建临时字典。
  • 如果我现在想删除特定项目怎么办 self.items[item.category].pop(item.name) 似乎不起作用
  • 不确定。使用调试器在该行停止或在该行之前打印self.items[item.category] 的值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-05
  • 2013-07-17
  • 1970-01-01
  • 1970-01-01
  • 2013-01-29
  • 1970-01-01
  • 2021-12-05
相关资源
最近更新 更多