faqts : Computers : Programming : Languages : Python : Snippets : Dictionaries

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

19 of 38 people (50%) answered Yes
Recently 9 of 10 people (90%) answered Yes

Entry

Sorting a dictionary by its values

Jul 23rd, 2002 07:32
Andreas Pietrusky, Nathan Wallace, unknown unknown, Hans Nowak, Snippet 56, Tim Ottinger


"""
Packages: basic_datatypes.dictionaries;sorting
"""

"""
Of course dictionaries can't be sorted, so you have to make a list.
But some of the other solutions look complex to me, and this looks
really simple. Will it do?
"""

def sorted(x):
    x.sort()
    return x
thelist=[]
for i in sorted( theDict.keys() ):
    thelist.append( (i,theDict[i]) )

"""
My example:

>>> dict
{'M': 'Steve Majewski', 'R': 'Guido van Rossum', 'H': 'Mark 
Hammond', 'P':
'Tim Peters'} 
>>> thelist=[] 
>>> for i in sorted( dict.keys() ): 
... 	  thelist.append( (i,dict[i]) ) 
... 	 
>>> thelist [('H', 'Mark Hammond'),
('M', 'Steve Majewski'), ('P', 'Tim Peters'), ('R', 'Guido van Rossum')]
>>> 
"""