Reputation: 907
I am trying to compute the euclidean distance among the dictionary elements as shown below
#!/usr/bin/python
import itertools
from scipy.spatial import distance
def Distance(data):
for subset in itertools.combinations(data, 2):
print subset
#This shows a tuple of two element instead of the elements of the dictionary.
dst = distance.euclidean(subset)
if __name__ == "__main__":
data = {}
data['1'] = [5, 3, 4, 4, 6]
data['2'] = [1, 2, 3, 4, 5]
data['3'] = [3, 1, 2, 3, 3]
data['4'] = [4, 3, 4, 3, 3]
data['5'] = [3, 3, 1, 5, 4]
Distance(data)
The issue is that when I try to compute the combination of the dictionary elements I get something that I do not expect, as commented in the code. I think I am doing something wrong with itertools.combinations...
Upvotes: 2
Views: 1318
Reputation: 6154
You're taking combinations of an iteration, and the iteration is:
for element in data:
print(element)
If you run that code, I think you'll see the issue: you're iterating over the keys of the dictionary, not the elements. Try again with .values()
:
for subset in itertools.combinations(data.values(), 2):
print subset
You have a couple of other issues in your code though: Firstly distance.euclidean
takes 2 parameters, so you'll need to do something like this:
dst = distance.euclidean(*subset)
...or this...
dst = distance.euclidean(subset[0], subset[1])
...and secondly your function isn't doing anything with dst
, so it will be overwritten every time through your loop.
Upvotes: 3