Sorting a SortedDictionary Requires a Different Key from OrderedDict

224 Views Asked by At

I am having trouble sorting a dictionary based on key values, which are originally strings. I am looking for a solution that uses SortedDict. Below I cast the strings to int, but the sorting seems irrational.

#using Jenks' library:
from sortedcontainers.sorteddict import SortedDict

mydict = SortedDict(
        lambda k: int(k[0]),
        {
        '1': '#fe70ac',
        '10': '#ff7400',
        '11': '#b6a2d1',
        '12': '#79bc3b',
        '100': '#000000',
        '101': '#000000',
        '102': '#000000'
        })

Returns

SortedDict_items(
[('11', '#b6a2d1'),
('10', '#ff7400'),
('12', '#79bc3b'),
('1', '#fe70ac'),
('102', '#000000'),
('100', '#000000'),
('101', '#000000')....
1

There are 1 best solutions below

1
On BEST ANSWER

It will work if you replace int(k[0]) with int(k) because otherwise you're sorting your dict based on the first digit of the key.