简体   繁体   English

在Python中对字典进行排序

[英]Sorting a dict in Python

I want to sort the dict in python. 我想在python中对字典进行排序。 As I am new I don't know where I am going wrong. 由于我是新手,所以我不知道我要去哪里。 The below code does sort but the first two entries only. 以下代码仅对前两个条目进行排序。

Pls advice 请咨询

scorecard ={}
result_f = open("results.txt")

for line in result_f:
    (name,score) =line.split()
    scorecard[score]=name

for each_score in sorted(scorecard.keys(),reverse =True):
    print('Surfer ' + scorecard[each_score]+' scored ' + each_score)

result_f.close()

My guess is you are keeping the scores as strings rather than integers. 我的猜测是您将分数保留为字符串而不是整数。 Strings do not sort the same way as integers. 字符串的排序方式与整数不同。 Consider: 考虑:

>>> sorted(['2','10','15'])
['10', '15', '2']
>>> sorted([2, 10, 15])
[2, 10, 15]

An aside: You map from score to surfer -- the mapping should be reverse of that. 顺便说一句:您是从得分到冲浪者的映射-这种映射应该是相反的。 Otherwise you would not be able to store two surfers with the same score. 否则,您将无法存储两个得分相同的冲浪者。

With changes to reverse the mapping and handle the score as an integer: 进行更改以反转映射并将分数作为整数处理:

s = '''Fred 3
John 10
Julie 22
Robert 10
Martha 10
Edwin 9'''

scorecard = {}
for line in s.split('\n'):
    name, score = line.split()
    scorecard[name] = score

keyfunc = lambda item: (int(item[1]), item[0]) # item[1] is cast to int for sorting
for surfer, score in sorted(scorecard.items(), key=keyfunc, reverse=True):
    print '%-8s: %2s' % (surfer, score)

result: 结果:

Julie   : 22
Robert  : 10
Martha  : 10
John    : 10
Edwin   :  9
Fred    :  3

If you want the first names in alphabetical order and the scores in descending order change keyfunc to keyfunc = lambda item: (-int(item[1]), item[0]) and remove reverse=True from sorted . 如果你想按降序排列变化按字母顺序排列的名字和分数keyfunckeyfunc = lambda item: (-int(item[1]), item[0])并删除reverse=Truesorted

With these changes, the result is: 经过这些更改,结果是:

Julie   : 22
John    : 10
Martha  : 10
Robert  : 10
Edwin   :  9
Fred    :  3

I guess your input file consists lines like 我猜你的输入文件包含如下行

cory 5
john 3
michael 2
heiko 10
frank 7

In that case, you have to convert the score value to an integer to sort properly: 在这种情况下,您必须将得分值转换为整数才能正确排序:

scorecard ={}
result_f = open("results.txt")

for line in result_f:
  (name,score) =line.split()
  scorecard[int(score)]=name

for each_score in sorted(scorecard.keys(),reverse =True):
  print('Surfer ' + scorecard[each_score]+' scored ' + str(each_score))

result_f.close()

If two names might have the same score, perhaps just store scorecard as a list: 如果两个名字的分数相同,则可以将记分卡存储为列表:

scorecard = []
with open("results.txt") as result_f:
    for line in result_f:
        name,score = line.split()
        scorecard.append((score,name))

for score,name in sorted(scorecard,reverse =True):
    print('Surfer ' + name +' scored ' + str(score))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM