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

Viewed 219

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!

2 Answers

From the documentation: http://www.grantjenks.com/docs/sortedcontainers/sorteddict.html

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})
Related