Python:对嵌套字典排序
我有一个嵌套字典,类型如下:
{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的元素数量,那么就返回完整的列表。
有什么想法或者建议吗?谢谢!
1 个回答
3
你可以在 list.sort()
中使用 key
参数。假设外层的字典叫做 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)