Why does this work in jython and not in python?
Jeremy Hylton
jeremy at zope.com
Wed Jun 18 13:49:49 EDT 2003
On Wed, 2003-06-18 at 13:01, Roman Milner wrote:
> I'm sorting a list of dictionaries based on a particular key. Using
> the code below, the list gets sorted in jython, but not in python. I'm
> using python 2.2.1 and jython 2.1.
>
> I really appreciate any help.
>
> ^Roman
>
> # if you run this with jython, you get a sorted list
> # with python the list stays in the same order. Why?
>
> tdict = [{'a':5}, {'a':3},{'a':4},{'a':2},{'a':1}]
>
> def sort_func(one, two):
> return one['a'] < two['a']
>
> print tdict
> tdict.sort(sort_func)
> print tdict
I don't understand why it works in jython. The problem is that your
sort_func is returning the wrong value.
It should return -1 if one < two, 1 if one > two, and 0 if equal. The
sort_func() will always report that two values are greater than or equal
to each other. Try this instead:
def sort_func(one, two):
return cmp(one["a"], two["a"])
Jeremy
More information about the Python-list
mailing list