2011-11-21 127 views
0

我有类型的嵌套字典以下蟒蛇:排序嵌套的字典

{id_1 : [ {id_2:score},{id_3:score_2} .... and so on],id_2 :[{id_1:Score_!....]} 

所以基本上嵌套的字典 现在我想排序每个主ID本词典得分 的基础所以基本上

{id_1: [{element with max_score},{element_with next max_score....}]... id_2:[{element_with max_score},{element_with next maxx score}...] 

也,函数应该带参数的说(N),返回前n位的匹配或如果N <数ID的元素则返回格兰完整列表 任何标识eas /思想.. 谢谢

+0

你可能在第一个代码片段中有一个虚假支架 - 你可以pl轻松审查这个? –

+0

为什么是内部列表字典的值,而不仅仅是元组? –

+0

@SvenMarnach yepp yepp。感谢您指出这一点..基本上它是一个嵌套的字典 – Fraz

回答

4

您可以使用key参数list.sort()。假设外词典被称为d,代码看起来是这样的:

for scores in d.itervalues(): 
    scores.sort(key=lambda x: next(x.itervalues()), reverse=True) 

lambda函数只是提取字典的单个值。

我想你会更好用,而不是作为字典列表的值的元组:

{id_1: [(id_2, score_2), (id_3, score_3),...], id_2: [(id_1, score_1),...]} 

使用这种数据结构,排序代码将

for scores in d.itervalues(): 
    scores.sort(key=lambda x: x[1], reverse=True) 

或等价,但稍快

for scores in d.itervalues(): 
    scores.sort(key=operator.itemgetter(1), reverse=True) 
+0

应该是'scores.sort(...)'? –

+0

那么d列表或嵌套代码? – Fraz

+0

@ F.J:你说得对,已经纠正了。 –