首页 > 解决方案 > 更改键值对并将其添加到python中的字典

问题描述

我创建了一个 Pizza 类,并尝试使用添加浇头方法。我以为您通过 do 将键值对添加到字典中dictionary_name['keyname'] = value,那么为什么会出现此错误:

Traceback (most recent call last):
  File "filepath", line 26, in <module>
    x.add_topping('apple', 0)
  File "filepath", line 21, in add_topping
    self.available_toppings[str(topping)] = self.available_toppings[topping] + amount
KeyError: 'apple'

我的披萨课

class Pizza:
    def __init__(self):
        self.radius = 1
        self.toppings = set()
        self.available_toppings = {}

    def __str__(self):
        top = ''
        for topping in self.available_toppings:
            top += str(topping) + ' '
        if self.toppings == {}:
            top = 'nothing'
        return 'A pizza with a radius of ' + str(self.radius) + ' and covered in ' + top + '.'

    def add_topping(self, topping: str, amount: int):
        if not isinstance(topping, str):
            raise ValueError('Sorry pal, but a topping must be a string')
        if not isinstance(amount, int):
            raise ValueError('Sorry pal, but the amount must be an integer')
        if topping not in self.toppings:
            self.available_toppings[str(topping)] = self.available_toppings[topping] + amount
        pass

标签: python

解决方案


如果不是字典中的键,则在 rhs 上将self.available_toppings[topping]提高;在这种情况下,您可能希望假设数量为零。因此,您可以改用以下内容:KeyErrortopping

self.available_toppings.get(topping, 0)

甚至更好地使用defaultdict

self.available_toppings = defaultdict(int)

然后您可以使用您的代码而无需任何进一步的更改。


推荐阅读