2016-01-23 160 views
4
dict = {a:[2, 4, 5], b:[4, 6, 7], c:[3, 1, 1]} 

使用上述作为例子的最高值的字典,我怎么会变成这样字典排序和打印,以便它显示为:排序由嵌套列表

>>>sorthighest(dict) 
b : 7 
a : 5 
c : 3 

我敢肯定的方式来去做这是通过沿max(dict[i])for:循环沿线做一些事情,但我不能得到任何工作。

+0

你想只在输出最高值,我们要保留的剩余部分,以及地方? – bereal

+0

@bereal只是最高值 – D3107

回答

4

不要使用名称dict,它会影响内建字典。您可以创建一个字典映射您的一部开拓创新的键子列表的最大值:

>>> d_max = {k:max(d[k]) for k in d} 
>>> d_max 
{'a': 5, 'c': 3, 'b': 7} 

然后遍历该字典的所有排序项:

>>> for k, v in sorted(d_max.items(), key=lambda x: x[1], reverse=True): 
...  print('{} : {}'.format(k,v)) 
... 
b : 7 
a : 5 
c : 3 

编辑:如果你永远需要在d_max字典,以查找的最高值,我们可以简化远一点:

>>> for k,v in sorted(((max(d[k]), k) for k in d), reverse=True): 
...  print('{} : {}'.format(v,k)) 
... 
b : 7 
a : 5 
c : 3 
2
for i in sorted(dict, key= lambda x: max(dict[x]), reverse=True): 
    print(i,max(dict[i])) 
2

一个字典重新无序。要创建一个有序字典使用collections.OrderedDict如下:

from collections import OrderedDict 

d = {'a': [2,4,5], 'b': [4,6,7], 'c': [3,1,1]} 
modified = {k: max(v) for k, v in d.items()} 
answer = OrderedDict(sorted(modified.items(), key=lambda x: x[1], reverse=True)) 
print(answer) 

输出

OrderedDict([('b', 7), ('a', 5), ('c', 3)]) 

然后,您可以轻松地遍历您下令字典如下:

for k, v in answer.items(): 
    print('{} : {}'.format(k, v)) 

输出

b : 7 
a : 5 
c : 3 
1

编辑:现在它还返回键。

sorted([(i,max(dict[i])) for i in dict], reverse=True, key=lambda x:x[1]) 

它返回:

[('b', 7), ('a', 5), ('c', 3)] 
+1

你失去了钥匙 – timgeb

+0

你是对的,我误解他只想要最高价值。 – ruggfrancesco