-3

I am trying to order all of the scores in order of each user's score from highest to lowest. I have attempted this with the code below:

import collections 
from collections import defaultdict
from operator import itemgetter

worker_scores = collections.defaultdict(lambda: collections.deque(maxlen=3))
import operator

worker_scores.clear() 

with open('score_names.txt') as f:
     for line in f: 
        worker,score = line.split(":")
        worker_scores[worker].append(int(score)) 

print("\nThis prints all the highest scores.\n")

for worker in sorted(worker_scores, key=itemgetter(1,2,3), reverse=True):
   print(worker," ".join(map(str,worker_scores[worker])))

   # This should print the maximum value for each key
   print max(worker_scores, key=worker_scores.get)

My text file also appears as follows:

AdamJohnson:10
AdamJohnson:20
AdamJohnson:30
AdamJohnson:40
AdamJohnson:60
AdamJohnson:50 
MichaelJordan:70
MichaelJordan:80
MichaelJordan:100
MichaelJordan:90
DavidSnowman:15
DavidSnowman:20
DavidSnowman:30
DavidSnowman:25

The outcome of the IDLE is as follows:

This prints all the highest scores.

MichaelJordan 80 100 90
AdamJohnson 40 60 50
DavidSnowman 20 30 25

This is what I desired, where the highest scores are at the top and the lowest scores are at the bottom. I discovered the itemgetter technique to do this so I have now accomplished part of my solution.

For the second part, I want the maximum key for each value to be printed. I can use the sorted key to print the keys in alphabetical order, but I cannot print the maximum value for each key. I have used this line from above:

print max(worker_scores, key=worker_scores.get)

To get this result:

AdamJohnson:60
MichaelJordan:100
DavidSnowman:30

But this error arrives: Invalid Syntax (Max). What is going wrong?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Delbert J. Nava
  • 121
  • 1
  • 9
  • @jonrsharpe Look sir, I am purely doing this code for my own benefit. What suggests that I am doing it for any qualification??? I do apologise but I feel offended. I have only been looking at other people's projects on SO to help develop my own program with my own understanding. Please do not suggest that I am plagiarising my own work as this undermines my own intentions. – Delbert J. Nava Feb 22 '15 at 09:25
  • @jonrsharpe I am not enrolled in a GCSE qualification as I am already in college. I shall then delete this question and ask a new one. Apologies for my outburst, since you have apologised too, and I will take your comments onboard. Thanks. – Delbert J. Nava Feb 22 '15 at 09:31
  • @DelbertJ.Nava All you need here is using sorted function to sort your dictionary items then add to an `OrderedDict`, and about asking such questions i have saw that many peoples that have a repo more than 100K answered such questions also homework questions and ....! i don't think that this questions has much problem!! – Mazdak Feb 22 '15 at 09:35
  • @KasraAD Thank You. I understand his opinion, but when I am confused, it is evident that I will need help. I will re - edit the code shortly and I will notify you to see if it is correct or not. – Delbert J. Nava Feb 22 '15 at 09:39
  • @KasraAD I will briefly display this code and then delete all of my posts as I do not want other pupils taking this qualification to be notified of such ways to cheat their quailfication. – Delbert J. Nava Feb 22 '15 at 09:42
  • 2
    @DelbertJ.Nava there is no need to delete your question you just need to edit it and show us that what you tried for solve your problem!;) – Mazdak Feb 22 '15 at 09:44
  • @KasraAD sure will do! – Delbert J. Nava Feb 22 '15 at 09:46
  • 2
    @DelbertJ.Nava : Please don't delete all of your old questions! We have **many** people asking questions about these GCSE tasks on Stack Overflow, so you can't blame us for being a little suspicious, especially when we see multiple questions about these tasks from the same person. I suggest that if you want to ask further questions related to this task that you explicitly state in the question that you are aware this is a GCSE task, but that you are doing it for your own self-study, not the GCSE. – PM 2Ring Feb 22 '15 at 09:52
  • @PM2Ring I understand, but now I will be unable to post any more questions due to the number of unlawful rating downs and also where it is perceived that I have cheated a qualification that does not exist in the area that I live. – Delbert J. Nava Feb 22 '15 at 10:01
  • You are using Python 3, in Python 3, `print` is a function `print(max(...))` – Antti Haapala -- Слава Україні Feb 22 '15 at 10:01
  • @KasraAD the question has been updated. Please inform me how to solve my problem. – Delbert J. Nava Feb 22 '15 at 10:01
  • @AnttiHaapala but this is what is returned for each person: `MichaelJordan:` just nothing. No highest score. Just absolutely nothing. And the same happens for the other keys in my dictionary too. Would it be possible if you wrote your answer as a response to my questions as I am being restricted to comment on my own question (says please use extended chat.) – Delbert J. Nava Feb 22 '15 at 10:03
  • @DelbertJ.Nava: Extended Chat is good! It will save a permanent copy of all these comments in a special chatroom connected with this question. – PM 2Ring Feb 22 '15 at 10:12
  • @PM2Ring Thank you very much Sir! I do apologise wholeheartedly for any coincidence to a qualification assignment at such GCSE level. Please do understand that I have developed my own tasks to myself based on other posts across SO, so I will continue developing my quiz when time is available, since I have a vacation from my college this term. Thanks once again for your comments, and if I require your help, I will tag you when appropriate! Thanks! – Delbert J. Nava Feb 22 '15 at 10:15
  • @jonrsharpe dear mr sharpe, I have researched the GCSE tasks online, and I have immediately noticed that the submission dates for these tasks is June 2016 to an assessor named 'Oxford Cambridge and RSA Examinations' . If I were a GCSE pupil, it would be highly unlikely that I would complete an assignment 1 1/2 years before it is due to be submitted, considering it has taken me 1 month to complete my program to the level of functionality it has today. Thanks again. Delbert John Nava. – Delbert J. Nava Feb 22 '15 at 10:28

2 Answers2

1

Also, if I want to print out my dictionary in order of highest results to lowest results, I would need to use itemgetter(1) since I am looking at the second value, which has the highest score and then using the reverse property set to True in order to indicate that the dictionary must be printed with highest at the top and lowest to the bottom.

Please see Sort a Python dictionary by value if you do not understand. I have just found this answer.

Thanks again to @KasraAD and @AnttiHaapala, alongside @PM2ring for their support, and my apologies to @jonrsharpe. I have now successfully answered my own question!

This is the code:

for k,v in sorted(d.items(), key=itemgetter(1), reverse=True):
    print (':'.join((k,str(v))))
Community
  • 1
  • 1
Delbert J. Nava
  • 121
  • 1
  • 9
0

You don't need to use max, you can use sorted function and collections.OrderedDict :

d=OrderedDict()

for k,v in sorted(((i,j.pop()) for i,j in worker_scores.items()),key=operator.itemgetter(1),reverse=True):
    d[k]=v

print d
OrderedDict([('MichaelJordan', 100), ('DavidSnowman', 30), ('AdamJohnson', 60)])

All that i have done in preceding code is loop over the worker_scores items and pop the last (max) element in deque,(j.pop()) but note that you need to use reverse=True to have the desire order, then add them to OrderedDict.

And for print the items :

for k,v in d.items():
    print ':'.join((k,str(v)))

MichaelJordan:100
DavidSnowman:30
AdamJohnson:60
Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • Thanks! I have tried to print out your dictionary as `MichaelJordan:100`, `AdamJohnson:60` and `DavidSnowman:30` on my IDLE by using the following: `for worker in sorted(d): print(worker," ".join(map(str,d[worker])))` but this arrives: `TypeError: 'int' object is not iterable`. How can I solve this to print the desired outcome above? – Delbert J. Nava Feb 22 '15 at 10:08
  • Thank you very much sir! @KasraAD I do apologise for any inconvenience that I have caused in my code. I may need to ask again on SO but please do understand that I am not entering any qualification, and I express my sincere doubts that any child will be able to use such complex methods including defaultdict and arrays to complete their assignment at such qualification levels. Thanks :) – Delbert J. Nava Feb 22 '15 at 10:13
  • @DelbertJ.Nava you're welcome! its OK such problems always happen for newcomers, also myself! ;) – Mazdak Feb 22 '15 at 10:15
  • 1
    yes my apologies, although I am now close to being unable to post due to the first comments regarding plagiarism and cheating, unfortunately. Thanks again for your help! I may require your assistance later! :( – Delbert J. Nava Feb 22 '15 at 10:17
  • I am surprised how your comment has been downvoted by 1, but I assume SO does not like this post. – Delbert J. Nava Feb 22 '15 at 10:58
  • @DelbertJ.Nava its not SO its a person that has not any reason for his down vote because if he (she) has any reason surely cared about comment! :) – Mazdak Feb 22 '15 at 13:00