0

Let's say I have the following array of dicts:

>>> a =[{'md5': 'abc', 'title': 'something'}, {'md5': 'zyx', 'title': 'something'}]

I can sort on the strings ascending as-is:

>>> sorted(a, key=lambda x: (x['title'], x['md5']))
[{'md5': 'abc', 'title': 'something'}, {'md5': 'zyx', 'title': 'something'}]

However, it appears I cannot do it in-line descendingly:

>>> sorted(a, key=lambda x: (x['title'], -x['md5']))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <lambda>
TypeError: bad operand type for unary -: 'str'

Is there a way to do this within the sorted(iterator, key=...) structure or what is the best way to do this?

David542
  • 104,438
  • 178
  • 489
  • 842
  • @ggorlen so it seems you can't do it with the builtin in python with a single sort? – David542 Nov 03 '20 at 00:39
  • 1
    I can't think of a way offhand, and if Martijn says so, I generally accept that as fact, especially since the answer is recent. Is efficiency critical here? If so, it might be worth more thinking. – ggorlen Nov 03 '20 at 00:42
  • @ggorlen yea I upvoted that one -- what a great answer. Thanks for pointing that out! – David542 Nov 03 '20 at 00:48
  • @ggorlen on a string it could be done by `-` on the chr if in asci (all my chars are): `>>> sorted(a, key=lambda x: (x['title'], [-ord(c) for c in x['md5']]))` `[{'md5': 'zyx', 'title': 'something'}, {'md5': 'abc', 'title': 'something'}]` – David542 Nov 03 '20 at 00:54
  • Yep, that seems like a significant assumption (also listed in the dupe thread), and if you're worried about speed you'd have to benchmark to see what's faster. My thinking is that the nested list comp per element should be precomputed and may still be more expensive than just calling sort twice. The sort time complexity is probably going to dominate either way. – ggorlen Nov 03 '20 at 01:10

0 Answers0