-1

I have the object:

{'2017-10-2': 0.09457282561051072, '2017-10-3': 0.06606813446091735, '2017-10-1': 0.13701336286945082, '2017-10-6': 0.08511672971024725 }

And would like to sort it by date ( but the type of keys is string, not datetime ). The response should like like:

{   
    '2017-10-1': 0.13701336286945082,
    '2017-10-2': 0.09457282561051072, 
    '2017-10-3': 0.06606813446091735, 
    '2017-10-6': 0.08511672971024725 
}

Was trying to find something using google ,but unsuccessfully.

Thanks in advance,

Vba_Beg
  • 453
  • 1
  • 6
  • 13
  • you can find ways to sort python dictionaries here: http://pythoncentral.io/how-to-sort-python-dictionaries-by-key-or-value/ –  Sep 20 '17 at 13:59
  • Isn't `sorted(d)` enough? Python is sorting after the bytevalue of a char and so `'0'<'1'<'9'` in this case it works just fine. – MegaIng Sep 20 '17 at 14:01
  • Dictionaries are not sorted. See here: https://stackoverflow.com/questions/27262266/dictionary-is-not-staying-in-order-python – GLR Sep 20 '17 at 14:01

1 Answers1

1

Dictionary can't be sorted, for that you have to use OrderedDict from collections module.

For datetime comparsion, you can use dateutils.parse

from dateutil.parser import parse
from collections import OrderedDict

d = {'2017-10-2': 0.09457282561051072, '2017-10-3': 0.06606813446091735, '2017-10-1': 0.13701336286945082, '2017-10-6': 0.08511672971024725}
print(OrderedDict(sorted(d.items(), key=lambda x: parse(x[0]))))
pacholik
  • 8,607
  • 9
  • 43
  • 55