Adam Thompson
Adam Thompson

Reputation: 13

Ways of comparing Dictionaries

I have a dictionary:

vd = {'Klein': [1,1,1], 'Fox-Epstein': [1,-1,0], 'Ravella': [-1,0,0]}

I need a procedure that iterates over the dictionary checking which entry is most similar to one provided as an argument. I have two procedures the first is nested in the second.

def policy_compare(sen_a, sen_b, voting_dict):
    a = 0
    for i in range(len(voting_dict[sen_a])):
        a += voting_dict[sen_a][i] * voting_dict[sen_b][i]
    return a

This returns the dot product of two of the selected entries.

def most_similar(sen, voting_dict):
    a = []
    for i in voting_dict.keys():
        score = policy_compare(sen,i, voting_dict)
        a += score
    return a

The second procedure is not complete for two reasons:

  1. At the moment it is returning an error and I can't see where I am going wrong.
  2. It just returns a list of the dot products (The one with the greatest dot product in the most similar), whereas I require the 'key' who's scalar product with the chosen sen is largest.

FULL error.

Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    most_similar('Klein', vd)
  File "/Users/anthony/Desktop/matrix/megalol.py", line 15, in     most_similar
a += score

TypeError: 'int' object is not iterable

Upvotes: 0

Views: 100

Answers (2)

xnx
xnx

Reputation: 25518

Here are some modifications to approach the solution you want:

vd = {'Klein': [1,1,1], 'Fox-Epstein': [1,-1,0], 'Ravella': [-1,0,0]}

def policy_compare(sen_a, sen_b, voting_dict):
    a = 0
    for i in range(len(voting_dict[sen_a])):
        a += voting_dict[sen_a][i] * voting_dict[sen_b][i]
    return a

def most_similar(sen, voting_dict):
    a = []
    for this_sen in voting_dict.keys():
        if this_sen == sen:
            continue
        score = policy_compare(sen, this_sen, voting_dict)
        a.append((this_sen, score))
    return max(a,key=lambda sen: sen[1])

print most_similar('Klein', vd)

As someone else has said, you want to append to your list a. I've added the senator's name along with the dot product in a tuple (for each item in a) because the dictionary keys come out in arbitrary order and you won't know which one is being referred to by each entry in a otherwise. I've returned the maximum dot product entry from most_similar. Also, to avoid comparing senators with themselves you want to use continue (go back to the start of the loop for the next iteration), not pass (do nothing and continue with the current iteration).

Upvotes: 1

Daniel
Daniel

Reputation: 1420

a is a list, score is an int. You can't add the two together. A list is iterated over in order to get the contents in order to add them to another - thus the "weird" error. It can't iterate over the int (score) in order to add it to the the list (a).

try a.append(score) to add score on to the end of it.

Upvotes: 2

Related Questions