mrmo123
mrmo123

Reputation: 725

Multiply key*value in a list inside a dictionary?

a = {u'1': ['abc', 'thanks', 2.0, 999.0],u'2': ['def', 'for', 2.0, 100.0],u'3': ['ghi', 'helping', 1.0, 99999.0],u'4': ['jkl', 'me', 3.0, 2120.0] etc:[etc]}

So I'm trying to have all multiply all the Dictionary { key : List [ blah, blah, numbers, numbers], key : List [ blah, blah, numbers, numbers ], etc} This is proving very troublesome :(. The output I want is 108557 which is derived from (2*999)+(2*100)+(1*99999)+(3*2120).

I found an answer here Multiply keys*values in a dict? that nearly solves my problem. In that he's able to multiply this dictionary a = {2: 4, 3: 2, 5: 1, 7: 1} to get an answer of 26 by using sum([key * val for key, val in a.items()]). I'm having trouble incorporating the list in this code! Thanks in advance for any help.

Upvotes: 1

Views: 1066

Answers (1)

Jesse the Game
Jesse the Game

Reputation: 2630

If the numbers are always the last two elements, you could do:

sum([val[-2] * val[-1] for val in a.values()])

edit updated with Blckknght's tip

Upvotes: 3

Related Questions