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

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

请帮助我理解为什么在以下代码中设置 SortedDictkey 参数:

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

出现以下错误:

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

如何修复示例? 非常感谢您的帮助!

sortedcontainer 文档说您错误地调用了 SortedDict 构造函数:

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.

来自文档: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.

您的代码应为:

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