I am trying to use SortedList from sortedcontainers library as a parameter for SortedDict. Even though the Initialization maps = SortedDict(SortedList())
worked. I am Unable to insert any data into the SortedDict maps
from sortedcontainers import SortedDict, SortedList maps = SortedDict(SortedList) maps[1] = [1,2]
I tried doing the above code but i got a TypeError:Int object is not Iterable
so i tried maps[‘a’] = [1,2] and it worked but I am unable to further add elements into maps['a'] using .add() or .update() methods of SortedList
.
I am only able to do so using .append()
method => maps['a'].append(0)
does work but it loses the functionality of SortedList as I got maps = {'a':[1,2,0]}
where list was unsorted.
So how can I get maps = {1:[1,2,4], 2:[8,9], 3:[1,5,6]}
in this way.
I have also tried using maps = SortedDict(lambda x:SortedList)
which worked for defaultdict, so I tried it here but it didn’t work.
Advertisement
Answer
You are passing the class SortedList
to the constructor of the SortedDict
. What do you expect that to do?
The documentation explains what it actually does:
Optional key-function argument defines a callable that, like the key argument to the built-in
sorted
function, extracts a comparison key from each dictionary key. If no function is specified, the default compares the dictionary keys directly. The key-function argument must be provided as a positional argument and must come before all other arguments.
So when trying to insert an entry, SortedDict
calls SortedList(1)
. This throws an error because the SortedList
constructor expects an iterable, but 1
is not iterable.
If you want a SortedDict
whose values are SortedList
objects, just create an empty SortedDict
and put only SortedList
objects into it:
maps = SortedDict() maps[1] = SortedList([1, 2])