Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a list of tuples alphabetically (case-sensitive)

I have a list of tuples

alist = [(u'First', 23), (u'Second', 64),(u'last', 19)]

I want to sort alphabetically (and case-sensitive) to get this:

(u'last', 19), (u'First', 23), (u'Second', 64)

I tried this:

sorted(alist, key=lambda x: x[0], reverse= True)

Unfortunately I get this:

(u'last', 19), (u'Second', 64), (u'First', 23),
like image 822
saromba Avatar asked Jan 14 '23 00:01

saromba


1 Answers

Include a key that indicates if the first character is uppercase or not:

>>> sorted([(u'First', 23), (u'Second', 64),(u'last', 19)], key=lambda t: (t[0][0].isupper(), t[0]))
[(u'last', 19), (u'First', 23), (u'Second', 64)]

False sorts before True so words with a lowercase initial will be sorted before words with a capital initial. Words are otherwise sorted lexicographically.

like image 158
Martijn Pieters Avatar answered Jan 17 '23 14:01

Martijn Pieters