Reputation: 51
I have a dictionary and that contains a list of two numbers each. I need to multiply those numbers together and keep a running total for all keys in the dictionary. I keep getting a TypeError:
sub = v1 * v2
TypeError: can't multiply sequence by non-int of type 'list'
I have tried to cast it to float, but then I get:
v1= float(c.get(k,v[0]))
TypeError: float() argument must be a string or a number, not 'list'
Code below:
change = {'penny': [.01,57], 'nickel':[.05,34],'dime':[.1,42], 'quarter': [.25,19],'half dallar':[.5,3],'one dollar bill':[1,24],'five dollar bill':[5,7],'ten dollar bill':[10,5],'twenty dollar bill':[20,3]}
def totalAmount(c):
total = 0
for k, v in c.items():
v1= c.get(k,v[0])
v2= c.get(k,v[1])
sub = v1 * v2
total = total + sub
totalAmount(change)
print("Total in petty cash: $" + total)
Upvotes: 2
Views: 91
Reputation: 11073
Try this:
change = {'penny': [.01,57], 'nickel':[.05,34],'dime':[.1,42], 'quarter': [.25,19],'half dallar':[.5,3],'one dollar bill':[1,24],'five dollar bill':[5,7],'ten dollar bill':[10,5],'twenty dollar bill':[20,3]}
def totalAmount(c):
total = 0
for k, v in c.items():
sub = v[0] * v[1]
total = total + sub
return total
t = totalAmount(change)
print(t)
output will be
181.72
and the problem with your code is v1= c.get(k,v[0])
.
you should change it to v1= c.get(k)[0]
if you want to use get
, but when you use .items()
you don't need to use get
. v
will be that desired array in each iteration.
Upvotes: 2
Reputation: 106598
The second parameter of the dict.get
method is for default value, not for further value retrieval.
You can unpack the values of the sub-lists like this instead:
for k, (v1, v2) in c.items():
sub = v1 * v2
total = total + sub
Upvotes: 2
Reputation: 403
v1= c.get(k,v[0])
v2= c.get(k,v[1])
In this situation v1
and v2
both get set to v
. c.get(i)
returns c[i]
, so c[k]
will naturally return the corresponding value v
. Instead just split your list up like this:
v1, v2 = v
Upvotes: 3