2017-05-26 146 views
0

我有一個字典,其鍵是一個整數,其值是一個列表。我想返回一個新字典,其中包含最低值爲list[0]的前n個字典條目。查找字典中列表的最大值 - python

舉例來說,如果我有這樣的

{1: [5, 'hello'], 2: [6, 'hi'], 3: [2, 'hey']} 

字典和n爲2,它會返回

{1: [5, 'hello'], 3: [2, 'hey']} 
+0

你有沒有嘗試過嗎? –

+0

是的,我只是想知道是否有一個更聰明的方法來做到這一點,也許使用一些很酷的python速記 –

回答

4

這應做到:

from heapq import nsmallest 
from operator import itemgetter 

d = {1: [5, 'hello'], 2:[6, 'hi'], 3:[2,'hey']} 

smallestN = dict(nsmallest(2, d.items(), itemgetter(1))) 

print(smallestN) 

你可以也可以不用導入heapqitemgetter

smallestN = dict(sorted(d.items(), key=lambda x: x[1][0])[:2]) 
+0

正是我所期待的!謝謝:) –

+0

@PaulRooney你是對的 - 感謝您的幫助。 – Darkstarone