Is it possible to sort a dictionary?
Rikard Bosnjakovic
rikbo716 at student.liu.se
Sun Mar 25 17:54:19 EST 2001
Victor Louie wrote:
> I was just wondering if anyone knows how to sort a dictionary by
> value...since the dictionary is <key: value> and where my value is a list.
You can't sort the actual dictionary since they're mapping. You can,
however, put the values in a list and sort the list. Something like
this:
for key in thedict.keys():
sortedlist.append( (key, thedict[key]) )
sortedlist.sort()
Test-run:
>>> foo = {"foo":[1,2,3], "bar":[2,3,4], "gazonk":[3,4,5]}
>>> foo
{'foo': [1, 2, 3], 'gazonk': [3, 4, 5], 'bar': [2, 3, 4]}
>>> sorted = []
>>> for key in foo.keys():
... sorted.append( (foo[key], key) )
...
>>> sorted.sort()
>>> sorted
[([1, 2, 3], 'foo'), ([2, 3, 4], 'bar'), ([3, 4, 5], 'gazonk')]
--
Rikard Bosnjakovic - http://a214.ryd.student.liu.se/cv/ - ICQ: 1158217
Anyone sending unwanted advertising e-mail to my address will be
charged $250 for network traffic and computing time. By extracting my
address from this message or its header, you agree to these terms.
More information about the Python-list
mailing list