Aiden Scott
Aiden Scott

Reputation: 13

How do I sort scores and names saved in a .txt file into alphabetical order with python?

import pickle
def startover():
    #Tells the user what number corresponds with what class.
    print('1 = classA, 2 = classB, 3 = classC')

    #accepts an input for what class the user would like to view.      
    Class=int(input('Choose the class you would like to view.'))

    #If class a is selected, open class a.
    if Class == int('1'):
        ClassA=open('Class6A.txt','rb')
        clsa=pickle.load(ClassA)
        print(clsa)


        #If class b is selected, open class b.
    if Class == int('2'):
        ClassB=open('Class6B.txt','rb')
        clsb=pickle.load(ClassB)
        print(clsb)


        #If class c is selected, open class c.
    if Class == int('3'):
        ClassC=open('Class6C.txt','rb')
        sorttype=int(input('How do you want to sort this data? 1=alphabetical 2=High to low by highest number 3=High to low by average number.'))
        clsc=pickle.load(ClassC)
        print(clsc)


    file=('Class6A.txt','rb')
startover()

I would like to be able to sort the selected code by the user, into alphabetical order so that they can find a name easily with the scores that the code outputs.

Inside Class6a.txt

:€}q (X    WHITE SAMq]q(KK  KeX   WILLIAMS GABRIELLEq]q(K
KKeX
   NATHAN WILSONq]q(KK  KeX   SMITH ISABELLEq]q(KK  KeX
   CLARK BRANDONq   ]q
(KKKeX   PATEL SAPNAq]q(KKKeX
   BROWN ADAMq
]q(KK
KeX   JONES CHLOEq]q(KKKeX
   DAVIS RYANq]q(K
KK  eX   MILLER NOELq]q(KKKeu.

Class6A.txt opened in python: {'WILLIAMS GABRIELLE': [10, 6, 2], 'JONES CHLOE': [7, 5, 5], 'MILLER NOEL': [1, 8, 6], 'CLARK BRANDON': [8, 6, 1], 'NATHAN WILSON': [7, 9, 6], 'SMITH ISABELLE': [2, 9, 6], 'WHITE SAM': [1, 9, 5], 'BROWN ADAM': [8, 10, 6], 'PATEL SAPNA': [7, 8, 7], 'DAVIS RYAN': [10, 6, 9]}

Upvotes: 1

Views: 614

Answers (2)

Vivek Sable
Vivek Sable

Reputation: 10213

  1. Use sorted() method to sort list by alphabets.
  2. Do calculation to find average of marks and create student list according to average marks

Demo:

import pickle

d = {'WILLIAMS GABRIELLE': [10, 6, 2], 'JONES CHLOE': [7, 5, 5],\
     'MILLER NOEL': [1, 8, 6], 'CLARK BRANDON': [8, 6, 1],\
     'NATHAN WILSON': [7, 9, 6], 'SMITH ISABELLE': [2, 9, 6],\
     'WHITE SAM': [1, 9, 5], 'BROWN ADAM': [8, 10, 6], 'PATEL SAPNA': [7, 8, 7],\
     'DAVIS RYAN': [10, 6, 9]}

with open("Class6A.txt", "wb") as fp:
    pickle.dump(d, fp)

import pickle
import collections

def getAverage(data):
    """ Create Average of student data """
    records = dict()
    for i, j in data.iteritems():
        records[i] = (j, float(sum(j))/len(j))

    return records

def startover():
    #. Tells the user what number corresponds with what class.
    print('1 = classA, 2 = classB, 3 = classC')
    #. accepts an input for what class the user would like to view.      
    while 1:
        try:
            class_no = int(raw_input('Choose the class you would like to view.'))
            if class_no not in [1,2,3]:
                print "Enter vlaid Class Number."
                continue
            break
        except ValueError:
            print "Enter valid Class Numner i.e.digit"
            continue

    #. If class a is selected, open class a.
    if class_no==1:
        file_name = 'Class6A.txt'
        #If class b is selected, open class b.
    elif class_no==2:
        file_name = 'Class6B.txt'
        #If class c is selected, open class c.
    elif class_no==3:
        file_name = 'Class6C.txt'

    while 1:
        try:
            sorttype = int(raw_input('How do you want to sort this data? 1=alphabetical\
             2=High to low by highest number 3=High to low by average number.'))
            if sorttype not in [1,2,3]:
                print "Enter vlaid option from the list.."
                continue
            break
        except ValueError:
            print "Enter valid option Number i.e. digit"
            continue

#    fp = open(file_name, 'rb')
#    data = pickle.load(fp)
#    fp.close()

    with open(file_name, "rb") as fp:
        data = pickle.load(fp)

    #- Add Average value in data.
    records = getAverage(data)

    if sorttype==1:
        student_names = records.keys()
        student_names = sorted(student_names)
    elif sorttype==3:
        student_names = []
        tmp = collections.defaultdict(list)
        for i, j in records.iteritems():
            tmp[j[1]].append(i)
        tmp1 = tmp.keys()
        tmp1 = sorted(tmp1)
        tmp1.reverse()
        for i in tmp1:
            student_names.extend(tmp[i])
    elif sorttype==2:
        student_names = []
        print "Try your self."

    print "Result:"
    print "Name\t Marks\t Average"
    for i in student_names:
        print "%s\t%s\t%s"%(i, records[i][0], records[i][1])


startover()

Output:

1 = classA, 2 = classB, 3 = classC
Choose the class you would like to view.1
How do you want to sort this data? 1=alphabetical             2=High to low by highest number 3=High to low by average number.1
Result:
Name     Marks   Average
BROWN ADAM  [8, 10, 6]  8.0
CLARK BRANDON   [8, 6, 1]   5.0
DAVIS RYAN  [10, 6, 9]  8.33333333333
JONES CHLOE [7, 5, 5]   5.66666666667
MILLER NOEL [1, 8, 6]   5.0
NATHAN WILSON   [7, 9, 6]   7.33333333333
PATEL SAPNA [7, 8, 7]   7.33333333333
SMITH ISABELLE  [2, 9, 6]   5.66666666667
WHITE SAM   [1, 9, 5]   5.0
WILLIAMS GABRIELLE  [10, 6, 2]  6.0

--------------------
1 = classA, 2 = classB, 3 = classC
Choose the class you would like to view.1
How do you want to sort this data? 1=alphabetical             2=High to low by highest number 3=High to low by average number.3
Result:
Name     Marks   Average
DAVIS RYAN  [10, 6, 9]  8.33333333333
BROWN ADAM  [8, 10, 6]  8.0
PATEL SAPNA [7, 8, 7]   7.33333333333
NATHAN WILSON   [7, 9, 6]   7.33333333333
WILLIAMS GABRIELLE  [10, 6, 2]  6.0
SMITH ISABELLE  [2, 9, 6]   5.66666666667
JONES CHLOE [7, 5, 5]   5.66666666667
WHITE SAM   [1, 9, 5]   5.0
MILLER NOEL [1, 8, 6]   5.0
CLARK BRANDON   [8, 6, 1]   5.0

if-elif-else

use if elif else when we want check multiple condition on same variable.

Demo:

>>> a = 51
>>> if a<0:
...   print "Number is negative."
... elif a==0:
...   print "Number is Zero."
... else:
...   print "Number is greater than 0"
... 
Number is greater than 0

Exception Handling:

Use try expet to catch Value Error exception during type casting.

demo:

>>> a = raw_input("Enter option:")
Enter option:f
>>> a
'f'
>>> int(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'f'
>>> try:
...   int(a)
... except ValueError:
...   print "Enter digit only.."
... 
Enter digit only..

Note:

Use raw_input for Python 2.x

Use input for Python 3.x

Upvotes: 2

bruno desthuilliers
bruno desthuilliers

Reputation: 77902

What you have in your pickle files are dict. You want to read the docs for dict.items() and the builtin sorted() function - this should be enough to solve your problem.

NB : I don't give you the exact (and quite simple) code as it indeed looks like homework.

Upvotes: 1

Related Questions