Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SortedDict key: TypeError: '<' not supported between instances of 'str' and 'int'

Please, help me to understand why setting key parameter of SortedDict in the following code:

from sortedcontainers import SortedDict
SortedDict({1:2, 0:1}) # works
SortedDict({1:2, 0:1}, key=lambda x: x) # TypeError
SortedDict({'a':2, 0:1}, key=lambda x: 1 if isinstance(x,str) else x) # TypeError

gives the following error:

TypeError: '<' not supported between instances of 'int' and 'str'

How can one fix the examples? Thank you very much for your help!

like image 552
S.V Avatar asked Oct 31 '25 21:10

S.V


1 Answers

From the documentation:

The key-function argument must be provided as a positional argument and must come before all other arguments.

Your code should thus read:

from sortedcontainers import SortedDict
SortedDict({1:2, 0:1})
SortedDict(lambda x: x, {1:2, 0:1})
SortedDict(lambda x: 1 if isinstance(x,str) else x, {'a':2, 0:1})
like image 124
Grismar Avatar answered Nov 03 '25 12:11

Grismar



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!