Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: sorting a list of tuples on alpha case-insensitive order

I have a list of tuples ("twoples")

[('aaa',2), ('BBB',7), ('ccc',0)]

I need to print it in that order, but

>>> sorted([('aaa',2), ('BBB',7), ('ccc',0)])

gives

[('BBB', 7), ('aaa', 2), ('ccc', 0)]

list.sort(key=str.tolower)

doesn't work (obviously), because

AttributeError: type object 'str' has no attribute 'tolower'

I don't want to change the strings in the list.

Another answer gave

list.sort(key=lambda (a, b): (a.lower(), b))

but that must be a Python 2 thing, because

SyntaxError: invalid syntax

... at the first (

itemgetter() doesn't help, because there's only one 'key' allowed

like image 847
ZZMike Avatar asked Jan 18 '26 02:01

ZZMike


1 Answers

You're right that this is a Python 2 thing, but the fix is pretty simple:

list.sort(key=lambda a: (a[0].lower(), a[1]))

That doesn't really seem any less clear, because the names a and b don't have any more inherent meaning than a[0] and a[1]. (If they were, say, name and score or something, that might be a different story…)


Python 2 allowed you to unpack function arguments into tuples. This worked (and was sometimes handy) in some simple cases, but had a lot of problems. See PEP 3113 for why it was removed.

The canonical way to deal with this is to just split the value inside the function, which doesn't quite work in a lambda. But is there a reason you can't just define the function out of line?

def twoplekey(ab):
    a, b = ab
    return a.lower(), b

list.sort(key=twoplekey)

As a side note, you really shouldn't call your list list; that hides the list type, so you can't use it anymore (e.g., if you want to convert a tuple to a list by writing list(tup), you'll be trying to call your list, and get a baffling error).

like image 62
abarnert Avatar answered Jan 19 '26 17:01

abarnert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!