我创建了一个这样的词典:
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)]}
我想按值对h1,h2,h3和h4中的值进行排序。
示例:
'h1':[('h4', 1.5), ('h3',2.5), ('h2',3.5)]
依此类推h2,h3和h4。
答案 0 :(得分:1)
"(...)的含义按值" 对h1,h2,h3和h4中的值进行排序是不明确的,但是从OP的示例输出判断,我认为他/她想要通过元组中的第二个元素(浮点数)对字典中的每个列表进行排序。这就是这本字典理解的作用:
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}
示例:
>>> 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)]
>>>
答案 1 :(得分:0)
使用for循环和itemgetter
:
from operator import itemgetter
for key, items in Dict.iteritems():
Dict[key] = sorted(items, key=itemgetter(1))