Why does this work in jython and not in python?

Skip Montanaro skip at pobox.com
Wed Jun 18 19:28:48 CEST 2003


    Roman> I'm sorting a list of dictionaries based on a particular
    Roman> key. Using the code below, the list gets sorted in jython, but
    Roman> not in python. I'm using python 2.2.1 and jython 2.1.

The function passed to sort must return three values, not two.  Try this
instead:

    tdict = [{'a':5}, {'a':3},{'a':4},{'a':2},{'a':1}]

    def sort_func(one, two):
        return cmp(one['a'],two['a'])

    print tdict
    tdict.sort(sort_func)
    print tdict

Here's output w/ Python 2.3b1+:

    >>> tdict = [{'a':5}, {'a':3},{'a':4},{'a':2},{'a':1}]
    >>> 
    >>> def sort_func(one, two):
    ...     return cmp(one['a'],two['a'])
    ... 
    >>> print tdict
    [{'a': 5}, {'a': 3}, {'a': 4}, {'a': 2}, {'a': 1}]
    >>> tdict.sort(sort_func)
    >>> print tdict
    [{'a': 1}, {'a': 2}, {'a': 3}, {'a': 4}, {'a': 5}]

That it worked for Jython 2.1 and not Python 2.2.1 was probably just due to
differences in the underlying implementation details.

Skip





More information about the Python-list mailing list