0

I want to sort the dict in 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()
1
  • 2
    You want us to diagnose this without knowing the input and output? Commented Oct 5, 2011 at 19:18

3 Answers 3

3

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.

With these changes, the result is:

Julie   : 22
John    : 10
Martha  : 10
Robert  : 10
Edwin   :  9
Fred    :  3
Sign up to request clarification or add additional context in comments.

5 Comments

wht version of python are you using ?
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32)
Thank you, but I have no clue what you have written as I have just started out. I will take atleast a day to figure this out
sorry, can you expalin what is happening here keyfunc = lambda item: (int(item[1]), item[0]) # item[1] is cast to int for sorting I don't understand it
See wiki.python.org/moin/HowTo/Sorting for how to use functions as keys when sorting. See secnetix.de/olli/Python/lambda_functions.hawk to learn about lambda functions.
2

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()

3 Comments

Also, storing the values in a dictionary like that will break if multiple entries have the same score.
@Frank I tried your method but then I am getting the below error print('Surfer ' + scorecard[each_score]+' scored ' + each_score) TypeError: Can't convert 'int' object to str implicitly
@user976847 you'll have to convert each_score to a string by using str() - see my example
1

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))

1 Comment

I can't I am currently doing this to learn dict in python. Reading from a book and nothing seems to work :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.