Sam
Sam

Reputation: 2605

Dot product with dictionaries

I am trying to do a dot product of the values of two dictionaries. For example:

dict_1={'a':2, 'b':3, 'c':5, 'd':2}
dict_2={'a':2, 'b':2, 'd':3, 'e':5 }

In list form, the above looks like this:

dict_1=[2,3,5,2,0]
dict_2=[2,2,0,3,5]

The dot product of the dictionary with the same key would result in:

Ans= 16  [2*2 + 3*2 + 5*0 + 2*3 + 0*5]

How can I achieve this with the dictionary? With the list, I can just invoke the np.dot function or write a small loop.

Upvotes: 11

Views: 7791

Answers (1)

Eugene Soldatov
Eugene Soldatov

Reputation: 10145

Use sum function on list produced through iterate dict_1 keys in couple with get() function against dict_2:

dot_product = sum(dict_1[key]*dict_2.get(key, 0) for key in dict_1)

Upvotes: 21

Related Questions