python - 类型错误 : unsupported operand type(s) for *: 'dict' and 'int'

标签 python dictionary

当我运行以下代码时,标题中出现错误。

amount = int(input('How many packs do you want?'))

pack = {'nuts':4.0,
        'bolts':300.0,
        'screws':140.0,
        'wire(m)':3.5}

for key,val in pack.items():
    total = pack * amount
    print(total,key)

我假设这是因为字典中的值不是整数。我该如何修复我的代码,以免出现此错误。

它应该打印这个人会收到的东西的数量,例如,如果有人订购了 2 包,它会打印:

8.0 坚果 600.0 bolt 280.0螺丝 7.0线(米)

最佳答案

您计算的 total 错误,您需要乘以 val 而不是 pack(这是一个字典)。请改用以下内容(total = val * amount 而不是 total = pack * amount):

for key,val in pack.items():
    total = val * amount
    print(total,key)

所以不是,原因不是字典中的值不是整数。

关于python - 类型错误 : unsupported operand type(s) for *: 'dict' and 'int' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30681566/

相关文章:

python - 使用 Pywinauto 自动化 ABBYY,我得到 "ElementNotFoundError"

c++ - std::map 赋值

python - 列表项之间的欧氏距离

python:更改基类属性

python - Q-Learning Table收敛到-inf

python - 如何对预测值进行反向移动平均(在 pandas 中,rolling().mean)操作?

python - 收集通过随机采样其他数据帧构建的数据帧的汇总统计信息

python - 覆盖字典 'update'方法

python - 将 csv 文件转换为字典列表

python - 如何从图像中准确提取数据?使用 PyTesseract