I need to sort some dictionary keys so that the u”/” character is at the end. When using non-unicode strings I did this with a function:
>>> L = ["/", "C", "b", "A"]
>>> sorted(L, key=lambda item: item.lower() if item != "/" else tuple())
['A', 'b', 'C', '/']
This uses (abuses?) the fact that tuples are sorted after strings in python. But unicode strings are sorted after tuples, so this won’t work if the keys are unicode. So, for example,
>>> L = [u"/", u"C", u"b", u"A"]
>>> sorted(L, key=lambda item: item.lower() if item != u"/" else tuple())
[u'/', u'A', u'b', u'C']
- What kind of objects are sorted after the unicode type?
- Is there a better way of doing this?
You don’t have to mix types or have a special sort key: just use a tuple as the key in all cases:
That means “/” is keyed as
(True, "/")while all other strings are(False, "...whatever...")