Sorting a dictionary

Andre Engels andreengels at gmail.com
Tue May 12 08:04:10 EDT 2009


On Tue, May 12, 2009 at 1:54 PM, Ronn Ross <ronn.ross at gmail.com> wrote:
> I'm attempting to sort for the results of a dictionary. I would like to
> short by the 'key' in ascending order. I have already made several attempts
> using: sorted() and .sort().
> Here is my loop:
>     for key,value in word_count.items():
>         print sorted(key), "=", value

That won't work. "key" will each time be the specific key, which you
then try to sort. Instead you want to sort the _set_ of pairs by their
first element. Luckily the default sort order of a tuple is by the value
of its first element, so you can do:

for key,value in sorted(word_count.items()):
   print key, "=", value





-- 
André Engels, andreengels at gmail.com



More information about the Python-list mailing list