michaelwb11
michaelwb11

Reputation: 51

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)

Upvotes: 2

Views: 91

Answers (5)

AGN Gazer
AGN Gazer

Reputation: 8378

total = sum(v1 * v2 for v1, v2 in change.values())

Upvotes: 1

Vinoth96
Vinoth96

Reputation: 353

[change[key][0]*change[key][1] for key in change.keys()]

Upvotes: 1

Mehrdad Pedramfar
Mehrdad Pedramfar

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

blhsing
blhsing

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

Mark Tyler
Mark Tyler

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

Related Questions