grantjenks / python-sortedcontainers

Python Sorted Container Types: Sorted List, Sorted Dict, and Sorted Set
http://www.grantjenks.com/docs/sortedcontainers/
Other
3.51k stars 203 forks source link

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

Closed timborden closed 1 year ago

timborden commented 1 year ago

Trying to reverse sort a SortedDict with an integer key I get a TypeError: '<' not supported between instances of 'int' and 'str' error.

>>> from sortedcontainers import SortedDict
>>> test = SortedDict(key=lambda x: -x)
>>> test[1] = "foo"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "...site-packages/sortedcontainers/sorteddict.py", line 299, in __setitem__
    self._list_add(key)
  File "...site-packages/sortedcontainers/sortedlist.py", line 272, in add
    pos = bisect_right(_maxes, value)
TypeError: '<' not supported between instances of 'int' and 'str'

Is this a bug? ....or am I setting up the key wrong?

grantjenks commented 1 year ago

To pass a key func, it must be positional else the kwargs are interpreted as a dict which is used for initialization. Read the docs for details

timborden commented 1 year ago

Gotcha...thanks for clarifying

>>> from sortedcontainers import SortedDict
>>> test = SortedDict(lambda x: -x)
>>> test[1] = "foo"
>>> test[3] = "bar"
>>> test
SortedDict(<function <lambda> at 0x1035e2ef0>, {3: 'bar', 1: 'foo'})

(in case someone else is having the same issue)