Python3: Using sorted(key=...)

MRAB python at mrabarnett.plus.com
Thu Aug 6 21:33:27 EDT 2009


Johannes Bauer wrote:
> Hello list,
> 
> I'm having trouble with a incredibly simple sort of a list containing
> ints and tuples:
> 
> def myorder(x):
> 	if type(x) == int:
> 		return x
> 	else:
> 		return x[0]
> 
> odata = sorted([ (a, b) for (a, b) in data["description"].items() ],
> key=myorder)
> 
You're sorting a list of tuples (key/value pairs), so 'myorder' is
always given a tuple.

> still says:
> 
> Traceback (most recent call last):
>   File "./genproto.py", line 81, in <module>
>     odata = sorted([ (a, b) for (a, b) in data["description"].items() ],
> key=myorder)
> TypeError: unorderable types: tuple() < int()
> 
> Why is that? Am I missing something very obvious?
> 
Are some keys 'int' and others 'tuple'? In Python 3.x you can't compare
them except for equality:


Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit 
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
 >>> (1, ) < 1
False


Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit 
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
 >>> (1, ) < 1
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: unorderable types: tuple() < int()



More information about the Python-list mailing list