Sorting a dict with tuples as values

十年热恋 提交于 2020-01-23 01:38:11

问题


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

回答1:


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)



回答2:


You're passing the key as the argument to, uh, key.

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



回答3:


You're attempting to sort on the keys of the dictionary, not the values. Replace your self.diffs.keys() call with self.diffs.items(), and then it should work (but do keep the lambda, or use operator.itemgetter(1). Tuples sort starting with the first element, so you don't have to worry about that.)


Just noticed that you only want the keys. With my suggestion, you'd have to wrap the sort with zip()[0] (making sure to unpack the resultant list of tuples from the sort by prefixing with * in the call to zip()).




回答4:


You're close. Try this instead:

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

You're sorting a list of keys, so you have to take that key back to the dictionary and retrieve element 1 in order to use it as a comparison value.



来源:https://stackoverflow.com/questions/6349296/sorting-a-dict-with-tuples-as-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!