python - 更改键值对并将其添加到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
解决方案
如果不是字典中的键,则在 rhs 上将self.available_toppings[topping]
提高;在这种情况下,您可能希望假设数量为零。因此,您可以改用以下内容:KeyError
topping
self.available_toppings.get(topping, 0)
甚至更好地使用defaultdict
:
self.available_toppings = defaultdict(int)
然后您可以使用您的代码而无需任何进一步的更改。
推荐阅读
- javascript - JAVASCRIPT,WebdriverIO- 如何使用 javascript 代码与 excel 表交互
- javascript - 列出多维数组的每个变体的可能方法/功能?
- qt - 如何使用 QT Quick Contol 2.0 为 TableView 中的一行赋予边框颜色?
- python - 比较两个列表并从第一个列表 Python 中获取唯一元素
- android - 如何使用远程消息启动 android 应用程序?
- regex - 如何用引号将所有单元格括起来?
- r - 使用 dplyr 仅过滤唯一值列表中的一个
- angular - 有没有办法让同一组件上的不同指令调用在它们之间进行通信?
- r - 更改ggboxplot中点的SIZE和ALPHA?(右)
- webpack - 使用 webpack 时未加载 scss 文件