txt将包含以下内容:
Matt Scored: 10
Jimmy Scored: 3
James Scored: 9
Jimmy Scored: 8
....
我设法放在一起的代码(对python很新)在这里:
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
函数时打印带有最高分数的名称,或者如果我使用itemgetter
它似乎只能起到最低或最高的作用。所以我想知道是否有人可以帮助我。任何事情都值得赞赏,请解释一下:)
python大神给出的解决方案
您可以使用此:
sorted_dict = OrderedDict(
sorted((key, list(sorted(vals, reverse=True)))
for key, vals in d.items()))
此代码段按字母顺序对名称进行排序,并且每个名称的得分从最高到最低。排序方法中的reverse
参数可用于强制顺序从最高到最低。
例如:
>>> 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])])