0

I am trying to sort a dictionary, "Highest" and "Average" from highest to lowest, but I can not get the dictionary to sort from the text file. I am not sure if I should be using an array instead or if there is a way around it?

This is my code:

import random 
score = 0 
print("Hello and welcome to the maths quiz!") 
while True: 
    position  = input("Are you a pupil or a teacher?: ").lower() 
    if position  not in ("teacher","pupil"): 
        print ("Please enter 'teacher' or 'pupil'!") 
        continue 
    else:
        break 

if position  == 'pupil':

your_name = ""
while your_name == "":
    your_name = input("Please enter your name:")  # asks the user for their name and then stores it in the variable name

class_no = ""
while class_no not in ["1", "2", "3"]:
    class_no = input("Please enter your class - 1, 2 or 3:")  # Asks the user for an input

score = 0

for _ in range(10):
    number1 = random.randint(1, 11)
    number2 = random.randint(1, 11)
    operator = random.choice("*-+")
    question = ("{0} {1} {2}".format(number1,operator,number2))

    solution = eval(question)

    answer = input(question+" = ")

    if answer == str(solution):
        score += 1
        print("Correct! Your score is, ", score , )

    else:
        print("Your answer is not correct")

class_no = ("Class " + class_no + ".txt")

print("Congratulations {0}, you have finished your ten questions!".format(your_name))
if score > 5:
    print("Your total score is {0} which is over half.".format(score))
else:
    print("Better luck next time {0}, your score is {1} which is lower than half".format(your_name, score))

with open(class_no, "a") as Student_Class:
    Student_Class.write(your_name) 
    Student_Class.write(",") 
    Student_Class.write(str(score)) 
    Student_Class.write("\n") 
else:
    while True: 
    Group = input("Which class would you like to view first? 1, 2 or 3?: ") 
    if Group not in ("1", "2", "3"):
        print ("That's not a class!")
        continue
    else:
        break

Group = ("Class " + Group + ".txt")

while True:
    teacherAction = input("How would you like to sort the results? 'alphabetical', 'highest' or 'average'?: ").lower() # Asks the user how they would like to sort the data. Converts answer into lower case to compare easily.
    if teacherAction not in ("alphabetical","highest","average"):
        print ("Make sure you only input one of the three choices!")
        continue
    else:
        break 


with open (Group, "r+") as scores: 
    PupilAnswer = {}
    for line in scores:
        column = line.rstrip('\n').split(',')
        name = column[0]
        score = column[1]

        score = int(score)

        if name not in PupilAnswer:
            PupilAnswer[name] = []
        PupilAnswer[name].append(score)
        if len(PupilAnswer[name]) > 3:
            PupilAnswer[name].pop(0)

if teacherAction == 'alphabetical': 
    for key in sorted(PupilAnswer): 
        print(key, PupilAnswer[key]) 

elif teacherAction == 'highest': 
    highest = {} 
    for key, value in PupilAnswer.items(): 
        maximum = max(value) 
        highest[key] = maximum               
    for key in sorted(highest, key=highest.get, reverse=True): 
      print (key, highest[key]) 

else: 
    for name in sorted(PupilAnswer): 
        average = [] 
        for key in (PupilAnswer[name]): 
            average.append(key) 

        length = len(average)
        total = 0 

        for key in (average): 
            total = total + (key) 
        totalAverage = (total)/length 

        print (name, totalAverage) 

print ("Thank you for using the quiz!") 
input("Press 'enter' to exit!") 
Idos
  • 15,053
  • 14
  • 60
  • 75
  • 1) sorted(d.values()) 2) SortedDict – Andrey Apr 24 '16 at 19:56
  • [Dictionaries in Python cannot be sorted!](http://code.activestate.com/recipes/52306-to-sort-a-dictionary/) – Akshat Mahajan Apr 24 '16 at 20:00
  • Your `for` loop within `highest` condition does not look right. – Greg0ry Apr 24 '16 at 20:05
  • @G. Fredericks - since the question was closed (in my opinion too fast since it's not about sorting the dictionary but displaying it in order) - have a close look at your `PupilAnswer`. You store arrays under each dictionary element. Each array seems to be storing different scores (and also only two first scores from your file). You probably miss out some scores and/or handle `PupilAnswer` incorrectly when looping through dict items. – Greg0ry Apr 24 '16 at 20:19

1 Answers1

0

There is no "sorted" in dictionaries. They are a set of key-value items. Un-ordered.
You can use an OrderedDict.

Idos
  • 15,053
  • 14
  • 60
  • 75
  • This does not answer the question. Dictionary cannot be sorted however you can display items in order. – Greg0ry Apr 24 '16 at 20:02
  • Title: "PYTHON Sorting from a dictionary", first sentence: "I am trying to sort a dictionary". As I see it, this perfectly answers the question. If you disagree, ofcourse, you may downvote the answer – Idos Apr 24 '16 at 20:03
  • Nope, if you read his code sample you will understand he is not asking how to sort the dictionary but how to display it in sorted order. – Greg0ry Apr 24 '16 at 20:06
  • @Greg0ry No you can't, because the dict DOESN'T HAVE AN ORDER – Natecat Apr 24 '16 at 20:06
  • @Natecat - I understand you did not read my comment properly since it's exactly what I'm saying. Question is not about sorting the dictionary but to display dictionary in order. Read code example from the question. – Greg0ry Apr 24 '16 at 20:07
  • @Greg0ry I answer the question explicitly asked, not an implicit question shown in the code sample – Natecat Apr 24 '16 at 20:10
  • @Natecat - a piece of advice - try to read comments you are commenting, your response appear aggressive and unfriendly especially that you are repeating some of the thesis. – Greg0ry Apr 24 '16 at 20:14