Python: sort list of tuples by alpha case case insensitive

I have a list of tuples ("twoples")

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

      

I need to print it in this 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 lines in the list.

Another answer gave

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

      

but it should be Python 2 because

SyntaxError: invalid syntax

      

... at the first (

itemgetter () doesn't help because only one "key" is allowed

+3


source to share


2 answers


You are correct that this is a Python 2 thing, but the fix is ​​pretty simple:

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

      

This is actually not so clear, because the names a

and b

have no more inherent meaning than a[0]

and a[1]

. (If they were, say, name

and score

or something else, it might be a different story ...)


Python 2 allowed you to unpack function arguments into tuples. This worked (and was sometimes convenient) for some simple cases, but there were many problems. See PEP 3113 for why it was removed.



The canonical way to handle this is to simply split the value inside the function, which doesn't quite work in lambda

. But is there a reason why you can't just define an off-line function?

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

list.sort(key=twoplekey)

      


As a side note, you really shouldn't be naming your list list

; which hides the type list

, so you can no longer use it (for example, if you want to convert a tuple to a list by writing list(tup)

, you will try to call your list and get an incomprehensible error).

+8


source


The following works in Python 3:

>>> my_list = [('aaa',2), ('BBB',7), ('ccc',0)]
>>> my_list.sort(key=lambda elem: elem[0].lower())
>>> print(my_list)
[('aaa', 2), ('BBB', 7), ('ccc', 0)]

      



The function for unpacking function arguments does not work in Python 3 (as you discovered), but from the wording of the question it seems that you only care about comparing the first element ( elem[0]

) of each tuple. This example concentrates on this and ignores the second element ( elem[1]

).

0


source







All Articles