Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a dict with tuples as values

I have a dictionary that looks like this:

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

Basically I need back a list of the keys in sorted order, that is sorted based on the rank field in the tuple.

My code looks something like this right now (diffs is the name of the dict above):

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

that right 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
like image 734
Till Avatar asked Jun 14 '11 19:06

Till


1 Answers

keys() only gives you keys, not values, so you have to use the keys to retrieve values from the dict if you want to sort on them:

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

Since you're sorting on rank, which is the first item in the tuple, you don't need to specify which item in the value tuple you want to sort on. But if you wanted to sort on raw_data1:

return sorted(self.diffs.keys(), key=lambda x: self.diffs[x][1], reverse=True)
like image 97
senderle Avatar answered Sep 19 '22 16:09

senderle