Sort dict alphabetically
28,390
Solution 1
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
Solution 2
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]))
Author by
Rutwb2
Updated on April 25, 2020Comments
-
Rutwb2 about 4 years
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))
-
Sorin about 9 yearsYou can keep it simpler with 'for key, value in sorted(storedlist.interitems())'
-
QuantumChris almost 3 yearsAs of python 3.6+, dictionaries are ordered.