-2

I have the dict

d = {a: (None,), 'b': (None,), 'c 9:00': (32400,), 'd 10:23': (37380,)}

I need to get

{'c 9:00': (32400,), 'd 10:23': (37380,), a: (None,), 'b': (None,)}

How?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Nomer77
  • 1
  • 1
  • 1
    What was wrong with the answers to https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value, possibly combined with https://stackoverflow.com/questions/18411560/sort-list-while-pushing-none-values-to-the-end? – mkrieger1 Aug 26 '22 at 10:58
  • Please provide enough code so others can better understand or reproduce the problem. – Robert Aug 26 '22 at 15:58

1 Answers1

1

You should first convert None values to some lager value (+ infinity) and then try to sort them, like

import math
for k,v in d.items():
    if v[0] == None:
        d[k[0]] = (math.inf,)

Now sorting by value

d_sorted = dict(sorted(d.items(), key = lambda x: x[1]))

output

{'c 9:00': (32400,), 'd 10:23': (37380,), 'a': (inf,), 'b': (inf,)}

Abhishek Kumar
  • 383
  • 4
  • 18