Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplying a list of items from a dictionary

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)
like image 998
michaelwb11 Avatar asked Dec 29 '25 04:12

michaelwb11


2 Answers

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
like image 64
Mark Tyler Avatar answered Dec 31 '25 17:12

Mark Tyler


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
like image 25
blhsing Avatar answered Dec 31 '25 17:12

blhsing