'TypeError: unsupported operand type(s) for *: 'dict' and 'int'
I get the error in the title when I run the following code.
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)
I assume that this is because the values in the dictionary are not integer's. how do I fix my code so it doesn't give me this error.
It should print the number of things the person would receive, for example, if someone ordered 2 packs it would print:
8.0 nuts 600.0 bolts 280.0 screws 7.0 wire(m)
Solution 1:[1]
You are calculating the total wrong, you need to multiply with val and not with pack (which is a dict). Use the below instead (total = val * amount instead of total = pack * amount):
for key,val in pack.items():
total = val * amount
print(total,key)
So no, the reason is not that the values in the dictionary are not integers.
Solution 2:[2]
It is because type(pack) is <class 'dict'> and type(amount) is <class 'int'>.
There is no methods available in class 'dict' that can do multiplication operation with integer type.
So as mentioned by mu you should multiply it by val.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Anshul Goyal |
| Solution 2 |
