0

I'm trying to find the shortest distance between 2 kd trees and am using the scipy function 'sparse_distance_matrix'. The result is returned in a dictionary of keys matrix of the form {(1,2):4.54}.

Its possible to retrieve the value using the following code but no method seems to work to get the key value since its in tuple form

sparsemin = sp.KDTree.sparse_distance_matrix(aKD,bKD,20)
m = min(sparsemin.itervalues())
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
  • The top votes answer to the proposed duplicate, http://stackoverflow.com/questions/3282823/get-key-with-the-least-value-from-a-dictionary, does not work here. This is a `sparse.dok` matrix; which is a subclass of dictionary. It has its own `get` method. – hpaulj Jul 26 '16 at 18:31

1 Answers1

1

min(sparsemin.items(), key=lambda item: (item[1], item[0])) will return a tuple with the minimum value and its key.

a = {(1,2): 2.54, (1, 0): 4.52}
min(a.items(), key=lambda item: (item[1], item[0]))
>> ((1, 2), 2.54)
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
  • Or somewhat easier, `min(a, key=a.get)`. (It will only return the key. Getting the value given the key is left as an exercise to the reader.) – Sven Marnach Jul 26 '16 at 13:52
  • This `a.get` is the top answer to the supposed duplicate: http://stackoverflow.com/questions/3282823/get-key-with-the-least-value-from-a-dictionary. It works in that case, but not here. `IndexError: index must be a pair of integers`. – hpaulj Jul 26 '16 at 18:27
  • This is a sparse `dok` dictionary; implemented as a subclass of the regular dictionary. – hpaulj Jul 26 '16 at 18:32