user4617305
user4617305

Reputation:

Sorting data in dictionaries by highest number in a list assigned as a value? python

How would i refer to the first, second and third element in a list that is assigned to a key in a dictionary form? The dictionary is a students name with a list assigned to it with their scores in. How do I refer to each of the scores in that list so that I can remove the smaller one, and later on calculate an average from these scores and print them. The dictionary looks like this

{'Student Example ': [5, 2], 'Student Name ': [2], 'Another Student ': [1]}

whilst the code im trying to use looks like

    viewscores = input ("Would you like to view the scoreboards? (Yes/No): ")
if viewscores == "Yes":
    classview = int (input ("What class board would you like to view? (1,2 or 3): "))
    print ("Sort class",classn,"scoreboard: ")
    print ("1. Alphabetically by students highscore")
    print ("2. By high score, highest to lowest")
    print ("3. By average score, highest to lowest")
    sorting = int (input("Enter sort type: (1,2 or 3): "))

    if classview == 1:
        if sorting == 1:
            highscores = ((k, classone[k]) for k in sorted(classone, key=classone.get, reverse=True))
            for k, v in highscores:
                listnum = len(v)
                while listnum > 1:
                    if (v[1]) < (v[0]):
                        del (v[1])
                print (v,k)

I get the error:

Traceback (most recent call last):
  File "C:\Users\emily_000\Desktop\test task 3 part two.py", line 116, in <module>
    if (v[1]) < (v[0]):
IndexError: list index out of range

How could I refer to the indexs of the lists so that I can find the highest score out of them , then sort (by highest to lowest, and alphabetically) . Then how could i refer to them so i can calculate an average out of the scores and organise by this number? using python 3.3.4

This is for a school project so could you explain how it works so I can understand, thank you for any help

Upvotes: 2

Views: 200

Answers (1)

aborsim
aborsim

Reputation: 121

As for your first question:

averagescores = {}
for k, v in highscores.items():
    averagescores[k] = float(sum(v))/float(len(v))

The above code will average out all the scores and put them in a new dictionary called 'averagescores'.

As for your second question, dictionaries by default are orderless. You can, though, get an ordered representation of the dictionary as tuples:

import operator
sortedscores = sorted(averagescores.items(), key=operator.itemgetter(1))

This will sort the scores from least to most by value.

Upvotes: 1

Related Questions