Sortin dictionaries in python

Oleg Broytmann phd at phd.pp.ru
Tue Mar 13 12:18:39 EST 2001


On Tue, 13 Mar 2001 costas at springmail.com wrote:
> Is there a simple way to sort a dictionary? It seems the only way to
> do this is by indirectly creating  a sorted list.

   There is no.

> And while on the topic of sorting lists. I tried sorting a list and
> wanted to to pass a compare function to the list.sort() method. The
> documentaion gives no example.
>
> import string
>
> x=['a','c','B']
>
> def ignoreCase(left, right):
>      if string.upper(left) < string.upper(right):
>          return -1
>      else:
>          return 1
>
> x.sort(ignoreCase(left, right))

   You are close:

x.sort(ignoreCase)

   Pass the function, not call it :)

   BTW, ignoreCase (like any other comparison function) should return 0 if
left == right!

Oleg.
----
     Oleg Broytmann            http://phd.pp.ru/            phd at phd.pp.ru
           Programmers don't die, they just GOSUB without RETURN.





More information about the Python-list mailing list