简体   繁体   English

使用多个值对python字典进行排序

[英]sorting python dictionary with more than one values

I have created a dictionary like this:我创建了一个这样的字典:

Dict={'h1':[('h2',3.5), ('h3',2.5), ('h4', 1.5)], 'h2':[('h1',2.4), ('h4', 5.3), ('h3',1.1)], 'h3':[('h4',4.2),('h2',7.3),('h1',2.1)], 'h4':[('h1',4.3),('h3',3.2),('h2',4.3)]}

I want to sort the values in h1, h2, h3 and h4 by values.我想按值对 h1、h2、h3 和 h4 中的值进行排序。

example:例子:

'h1':[('h4', 1.5), ('h3',2.5), ('h2',3.5)] 

and so on for h2, h3 and h4.依此类推 h2、h3 和 h4。

The meaning of "(...) sort the values in h1, h2, h3 and h4 by values" is ambiguous but judging from OP's example output, I think he/she wants to sort every list in the dictionary by the second element in the tuples (the floats). “(...) 按值对 h1、h2、h3 和 h4 中的值进行排序”的含义不明确,但从 OP 的示例输出来看,我认为他/她想按中的第二个元素对字典中的每个列表进行排序元组(浮点数)。 That's what this dictionary comprehension does:这就是这个字典理解的作用:

Dict={'h1':[('h2',3.5), ('h3',2.5), ('h4', 1.5)], 'h2':[('h1',2.4), ('h4', 5.3), ('h3',1.1)], 'h3':[('h4',4.2),('h2',7.3),('h1',2.1)], 'h4':[('h1',4.3),('h3',3.2),('h2',4.3)]}

{k:sorted(Dict[k], key=lambda x : x[1]) for k in Dict}

Example:例子:

>>> Dict={'h1':[('h2',3.5), ('h3',2.5), ('h4', 1.5)], 'h2':[('h1',2.4), ('h4', 5.3), ('h3',1.1)], 'h3':[('h4',4.2),('h2',7.3),('h1',2.1)], 'h4':[('h1',4.3),('h3',3.2),('h2',4.3)]}
>>> 
>>> Dict_sorted = {k:sorted(Dict[k], key=lambda x : x[1]) for k in Dict}
>>> 
>>> for elem in sorted(Dict_sorted):
...     print elem, Dict_sorted[elem]
... 
h1 [('h4', 1.5), ('h3', 2.5), ('h2', 3.5)]
h2 [('h3', 1.1), ('h1', 2.4), ('h4', 5.3)]
h3 [('h1', 2.1), ('h4', 4.2), ('h2', 7.3)]
h4 [('h3', 3.2), ('h1', 4.3), ('h2', 4.3)]
>>> 

Using for loop and itemgetter :使用 for 循环和itemgetter

from operator import itemgetter
for key, items in Dict.iteritems():
   Dict[key] = sorted(items, key=itemgetter(1))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM