Sortin dictionaries in python

Corran Webster cwebster at nevada.edu
Tue Mar 13 13:16:55 EST 2001


In article <3aae4757.68617130 at News.CIS.DFN.DE>, 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.

Dictionaries have no inherent order, but if you need to get at the items 
in a sorted order, you'd do something like:

keys = mydict.keys()
keys.sort()
for key in keys:
    # do stuff with mydict[key]

If the data that you are dealing with is something that is strongly 
ordered, you may be better off using someting like a list of tuples 
instead of a dictionary.

> 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.

Have a look at the Sorting Mini-HOWTO from the main python site.

http://www.python.org/doc/howto/sorting/sorting.html

This has a solution to the problem below, as well.

> import string
> 
> x=['a','c','B']
> 
> def ignoreCase(left, right):
>      if string.upper(left) < string.upper(right):
>          return -1
>      else:
>          return 1

I think that this will work, but a comparison function should return 0 
if the two strings are equivalent, just in case the sort method changes 
in a future version of Python.  The following is a better way of doing 
this:

def ignorecase(left, right):
    return cmp(string.upper(left), string.upper(right))

In fact, if you are using a Python which has string methods, you could 
write this as:

def ignorecase(left, right):
    return cmp(left.upper(), right.upper())

which will be slightly more efficient.

> x.sort(ignoreCase(left, right))

When passing a function you only need to pass the name of the function, 
not the function parameters:

x.sort(ignorecase)

tells sort to use the comparison function "ignorecase".  Sort expects 
this function to have the right number of arguments, do the right kind 
of things to the arguments, and return the right kinds of results.

Finally, if you don't want to have to define a separate function and 
just want to do a one-off sort, you could do the following one-liner:

x.sort(lambda left, right: cmp(left.upper(), right.upper()))

This is quick if you only sort once, but slow if you need to sort many 
lists in this way.

Regards,
Corran



More information about the Python-list mailing list