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')....
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.