Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dot product with dictionaries

Tags:

python

numpy

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.

like image 239
Sam Avatar asked Oct 12 '15 11:10

Sam


People also ask

Can Python dictionary have dot notation?

If you come from a JavaScript background, you may be tempted to reference a dictionary value with dot notation. This doesn't work in Python.

How do you check if a dictionary contains an item?

To check if a value exists in a dictionary, i.e., if a dictionary has/contains a value, use the in operator and the values() method. Use not in to check if a value does not exist in a dictionary.

Can you use append on dictionaries?

We can make use of the built-in function append() to add elements to the keys in the dictionary. To add element using append() to the dictionary, we have first to find the key to which we need to append to.

Can lists contain dictionaries?

Dictionaries can be contained in lists and vice versa.


1 Answers

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)
like image 147
Eugene Soldatov Avatar answered Sep 19 '22 06:09

Eugene Soldatov