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.
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.
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.
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.
Dictionaries can be contained in lists and vice versa.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With