Sorting a dictionary

Alex alex at somewhere.round.here
Mon Mar 13 16:06:31 EST 2000


> I have thousands of entries in a Python dictionary:
> 
> mydict
> 
> where the entries are:
> {'word1, word2', integer}
> 
> I'd like to sort the dictionary in decreasing order on the
> integer values.

# I'm assuming the strings are the keys.
assert mydict.has_key ('word1, word2') 

l = []

for key, value in mydict.items ():
    l.append ((value, key))

l.sort ()
l.reverse () # Gives decreasing order.

# Then you can munge this however.  I often end up 
# doing something like

m = []

for value, key in l:
    m.append ((key, value))

# ... to arrange things more conveniently.

Alex.



More information about the Python-list mailing list