簡體   English   中英

如何按值和鍵的多個條件對嵌套字典進行排序?

[英]How can I sort a nested dict by multiple criteria for values and keys?

我在 Python 中有一個要排序的嵌套字典。

在第一步中,我希望它按“點”排序。
如果所有“點”都相等,則使用“wins”。
如果“積分”和“勝利”相等,則應按照“巴西”、“摩洛哥”等球隊名稱進行排序。

我的字典是

list_of_team = {
    "Brazil": {"wins": 1, "loses": 1, "draws": 1, "goal difference": 0, "points": 4},
    "Spain": {"wins": 1, "loses": 1, "draws": 1, "goal difference": 0, "points": 4},
    "Portugal": {"wins": 1, "loses": 1, "draws": 1, "goal difference": 0, "points": 4},
    "Morocco": {"wins": 1, "loses": 1, "draws": 1, "goal difference": 0, "points": 4}
}

output 應如下所示:

Brazil  wins:1 , loses:1 , draws:1 , goal difference:0 , points:4

Morocco  wins:1 , loses:1 , draws:1 , goal difference:0 , points:4 

Portugal  wins:1 , loses:1 , draws:1 , goal difference:0 , points:4

Spain  wins:1 , loses:1 , draws:1 , goal difference:0 , points:4

sorted(list_of_team, key= lambda x: list_of_team[x].get("points"))

如果您想按“積分”和“獲勝”按降序排序,按球隊名稱按字典順序排序:

out = sorted(list_of_team, key= lambda x : (-list_of_team[x].get("points"), -list_of_team[x].get("wins"), x))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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