bradkwitz
bradkwitz

Reputation: 21

Finding the Dot Product of two different key-value lists within a single dictionary

I am using this method to create a dictionary where the keys are Names which are paired with a list of values

def create_voting_dict(strlist):
    return {line.split()[0]:[int(x) for x in line.split()[3:]] for line in strlist}

However, now I have to take the dot product of the values of two keys found in the dictionary. This new problem begins as follows:

def policy_compare(sen_a, sen_b, voting_dict):

I am having issues trying to find what to return in this situation. Any help is welcome! Thanks in advance!

Oh! An example of an expected outcome would look like this:

 ...voting_dict = {'Fox-Epstein':[-1,-1,-1,1],'Ravella':[1,1,1,1]}
 ...policy_compare('Fox-Epstein','Ravella', voting_dict)
 ...-2

Upvotes: 2

Views: 264

Answers (1)

Niklas Rosencrantz
Niklas Rosencrantz

Reputation: 26655

I hope this is what you need.

def create_voting_dict(strlist):
    return {line.split()[0]:[int(x) for x in line.split()[3:]] for line in strlist}

def dot(K, L):
   if len(K) != len(L):
      return 0

   return sum(i[0] * i[1] for i in zip(K, L))

def policy_compare(sen_a, sen_b, voting_dict):
    return dot(voting_dict[sen_a], voting_dict[sen_b])

voting_dict = {'Fox-Epstein':[-1,-1,-1,1],'Ravella':[1,1,1,1]}
print(policy_compare('Fox-Epstein','Ravella', voting_dict))

It returns -2.

Upvotes: 1

Related Questions