[英]python: sort a nested dictionary
我有以下类型的嵌套字典
{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的元素数,则返回完整列表中的任何想法/想法。
您可以使用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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.