簡體   English   中英

python:對嵌套字典進行排序

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM