![](/img/trans.png)
[英]Sort a dictionary in python by values but maintaining the key order for equal values
[英]How to order dictionary when some of the values are the equal?
我正在尋找一個包含分數key
和值names
的字典,並根據最高分數對其進行排序。 當兩個人的names
得分相等時,字典將無法正確排序。 如何解決這個問題?
我是一個非常菜鳥的程序員。 我已經在網上搜索過,但找不到答案。
def ranking_people():
dictionary = {
score_player_one : player_one,
score_player_two : player_two,
score_player_three : player_three
}
sorted_dictionary = sorted(dictionary.items(), key = operator.itemgetter(0), reverse = True )
print("The ranking is: " + str(sorted_dictionary))
我希望輸出為:
排名是:[(19,'John 1'),[19,Alice 2],(16,'Bob 3')]
實際輸出為:
排名是:[(19,'John'),(16,'Bob')]
字典中的每個鍵都必須是唯一的。 如果您執行以下操作:
my_dict[19] = 'John'
my_dict[19] = 'Alice'
約翰被愛麗絲覆蓋。 您可能希望將名稱用作鍵,將分數用作值,但前提是不要重復使用名稱(“ John 1”和“ John 2”,而不是“ John”和“ John”)。
更新:
使用元組列表解決問題的示例,您可以使用重復的名稱和分數:
from operator import itemgetter
def ranking_people():
scores = [(10, 'John'), (8, 'Alice'), (8, 'Bob'), (14, 'John')]
scores_sorted = sorted(scores, key=itemgetter(0))
print(scores_sorted)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.