Sorting dict with tuples as values

I have a structure that looks like this:

{'key_info':(rank,raw_data1,raw_data2),'key_info2':....}

Basically I need to return the list of keys in sorted order, which is sorted based on the rank field in the tuple.

my code looks something like this right now (diffs is the structure name above):

  def _sortRanked(self):
    print(type(self.diffs))
    return sorted(self.diffs.keys(), key=lambda x: x[1], reverse=True)

which now returns this when I run it:

return sorted(self.diffs.keys(), key=lambda x: x[1], reverse=True)
IndexError: string index out of range

I hope someone can understand and help me a little.

EDIT:

i changed it to:

  def _sortRanked(self):
    return sorted(self.diffs.keys(), key=lambda x: self.diffs[x][0], reverse=True)

Now I get a weird order for it to return data to. order (shutter speed and in the same field order as above):

R : 3.64486899669e-05 3605 11
P : 3.11612504885e-05 1528 4
C : 2.50018364323e-05 2316 7
Q : -3.49014288804e-05 152 2
T : -4.45535602789e-05 2623 11
Z : -0.000101817241062 491 6
q : -0.000301208352276 1812 19

full output here: http://pastebin.com/e4eTYvgN

+3
source share
4 answers

keys() , , dict, :

return sorted(self.diffs.keys(), key=lambda x: self.diffs[x], reverse=True)

rank, , , . raw_data1:

return sorted(self.diffs.keys(), key=lambda x: self.diffs[x][1], reverse=True)
+6

, , key.

[k for (k, v) in sorted(D.iteritems(), key=lambda x: x[1], reverse=True)]
+2

, . self.diffs.keys() self.diffs.items(), ( operator.itemgetter(1). , .)


Just noticed that you only need keys. According to my suggestion, you would have to wrap the sort with using zip()[0](be sure to unpack the resulting list of tuples from the sort using the prefix *on invocation zip()).

0
source

You're close Try instead:

return sorted(self.diffs.keys(), key = lambda x: self.diffs[x][0], reverse = True)

You are sorting a list of keys, so you need to return that key to the dictionary and extract element 1 to use it as a comparison value.

0
source

All Articles