使用元组作为值对字典进行排序

问题描述:

我有一本这样的字典:

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

基本上,我需要按键顺序返回键列表,该键列表是根据元组中的rank字段进行排序的.

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

我的代码现在看起来像这样(diffs是上面字典的名称):

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

keys()仅提供键,而不提供值,因此,如果要对它们进行排序,则必须使用键从dict中检索值:

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)

由于要对元组中的第一项rank进行排序,因此无需指定要对值元组中的哪个项进行排序.但是,如果您想对raw_data1进行排序:

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)