Search code examples
pythonsortingpython-3.xordereddictionary

Sorting DefaultDict() using key values in Python3.x


I have a dict which contains values like

DefaultListOrderedDict([('29.970', [1, 0, 0, 0, 0]), ('100.000', [0, 1, 0, 0, 1]), ('200.000', [0, 0, 1, 0, 0]), ('60.000', [0, 0, 0, 1, 0]), ('0.750', [0, 0, 1, 0, 0]), ('25.000', [0, 0, 0, 0, 1]), ('48.000', [0, 0, 1, 0, 0])])

I would like to sort it with values

I tried for k,v in sorted(Dict.items(),reverse = True):

But the sorting occurs in this order :

   ['0.750', '100.000', '200.000', '25.000', '29.970', '48.000', '60.000']

I don't understand the reason behind it. I would like to know the way how to sort it as :

   ['0.750', '25.000', '29.970', '48.000', '60.000', '100.000', '200.000']

Solution

  • You should convert keys to float:

    OrderedDict(sorted(your_dict.items(), key=lambda item: float(item[0])))