2017-04-02 109 views
1

我排序基於作爲在列表上第三元素(在值)的特定值的字典排序字典鍵與排序的值沿那些排序值對應於?打印通過使用

謝謝你的期待。

回答

1

使用items而不是keys

print(sorted(dict.items(), key=lambda item: item[1][2], reverse=True)[:3]) 

或保存排序鍵,並用它來獲取項目:

keys = sorted(dict, key=lambda key: dict[k][2], reverse=True)[:3] 
items = [(key, dict[key]) for key in keys] 
print(items) 

如果你想值seaparately:

keys = sorted(dict, key=lambda k: dict[k][2], reverse=True)[:3] 
values = [dict[key] for key in keys] 

BTW ,請勿使用dict作爲變量名稱;它陰影內置函數/類型dict

+0

謝謝,這是做的伎倆。而且我認爲你錯誤地將它鍵入k而不是鍵(在最後一段代碼中)。可能想改變這一點。乾杯! – Sherby

+0

@Sherby,你說得對。我修復了代碼。感謝您的評論。 – falsetru

0

您可以保存排序的列表並打印所需的格式。

sorted_list = sorted(dict.keys(), key=lambda k: dict[k][2], reverse=True)[:3] 
for key in sorted_list: 
    print 'key is '+ key + ' value is '+ sorted_list[key][3] 
+0

感謝您的帖子。然而,我得到這樣的錯誤:print'key is'+ key +'value is'+ sorted_list [key] [2] 「TypeError:列表索引必須是整數,而不是str」 – Sherby

+0

對不起。我想你應該使用這一行然後: print'key is'+ key [0] +'value is'+ key [3] – ida