Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort dict alphabetically [duplicate]

My program can output every student's name and their 3 scores from a dict in a file, but I need to sort the data by alphabetical order. How can I sort the names and scores alphabetically according to the surname?

This is my code so far: import pickle

def clssa():
    filename="friendlist.data"
    f=open('Class6A.txt','rb')
    storedlist = pickle.load(f)
    for key, value in storedlist.items():
        sorted (key), value in storedlist.items()  
        print (("{} --> {}").format(key, value))
like image 687
Rutwb2 Avatar asked Apr 14 '15 16:04

Rutwb2


2 Answers

Use the sorted keyword.

for key, value in sorted(storedlist.items()):
    # etc

How to sort dictionary by key in numerical order Python

https://wiki.python.org/moin/HowTo/Sorting

like image 126
Joe Avatar answered Sep 28 '22 15:09

Joe


Dictionaries are not ordered, so you have to sort the keys and then access the dictionary:

for key in sorted(storedlist.iterkeys()):
    print (("{} --> {}").format(key, storedlist[key]))
like image 37
enrico.bacis Avatar answered Sep 28 '22 15:09

enrico.bacis