如何排序字典从每个键的最高值到最低值打印? [英] How to sort a dictionary to print from highest value to lowest for each key?

查看:105
本文介绍了如何排序字典从每个键的最高值到最低值打印?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

txt将包含以下内容:

txt would contain a something like this:

Matt Scored: 10
Jimmy Scored: 3
James Scored: 9
Jimmy Scored: 8
....

我设法组合的代码(相当于python)在这里:

The code I managed to put together (quite new to python) is here:

from collections import OrderedDict
#opens the class file in order to create a dictionary
dictionary = {}
#splits the data so the name is the key while the score is the value
f = open('ClassA.txt', 'r')
d = {}
for line in f:
    firstpart, secondpart = line.strip().split(':')
    dictionary[firstpart.strip()] = secondpart.strip()
    columns = line.split(": ")
    letters = columns[0]
    numbers = columns[1].strip()
    if d.get(letters):
        d[letters].append(numbers)
    else:
        d[letters] = list(numbers)
#sorts the dictionary so it has a alphabetical order
sorted_dict = OrderedDict(sorted(d.items()))
print (sorted_dict)

我遇到的问题是尝试打印字典的名称和分数从最高到最低的是,它将只打印具有最高分数的名称,当使用 max 函数或如果im使用 itemgetter 它似乎只适用于最低到最高。所以我想知道是否有人能够帮助我。任何东西都是赞赏的,如果可能,解释一下:)

And the problem I encountered is when trying to print the dictionary with the names and the scores from highest to lowest is that it will either only print the name with the highest score when using the max function or if im using the itemgetter it only seems to work for lowest to highes. So I was wondering if anyone would be able to help me out. Anything is appreciated, explain it if possible :)

推荐答案

你可以使用这个:

sorted_dict = OrderedDict(
    sorted((key, list(sorted(vals, reverse=True))) 
           for key, vals in d.items()))

此代码段按字母顺序排列名称,每个名称的分数从最高到最低排序方法中的 reverse 参数可用于强制从最高到最低的顺序。

This snippet sorts the names in alphabetic order and the scores for each name from highest to lowest. The reverse parameter in sort methods can be used to force the order from highest to lowest.

例如:

>>> d = {"Matt": [2,1,3], "Rob": [4,5]}
>>> OrderedDict(sorted((key, list(sorted(vals, reverse=True))) for key, vals in d.items()))
OrderedDict([('Matt', [3, 2, 1]), ('Rob', [5, 4])])

这篇关于如何排序字典从每个键的最高值到最低值打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆