Sort DICT by Keys when they are DATETIME

Viewed 125

I'm trying to sort a DICT by Keys, but the big issue i founded first the KEYS values is a 'STRING' based on quarterly period.

Follow a example:

ex_dict = {
    "6/2021": 1,
    "9/2020": 1,
    "6/2019": 1,
    "3/2020": 1,
    "6/2020": 1,
    "9/2019": 1,
    "3/2021": 1,
    "3/2019": 1,
}

I know i can used the function sorted(), to order the keys then use list comprehension to order with original values.

Something like this:

in: print({k: v for k, v in sorted(ex_dict.items())})

out: {
   '3/2019': 1,
   '3/2020': 1,
   '3/2021': 1,
   '6/2019': 1,
   '6/2020': 1,
   '6/2021': 1,
   '9/2019': 1,
   '9/2020': 1
}

But he only orders using the first number, how i can transform this keys to DATETIME to make order on the right way.

3 Answers

you can use key option for example:

{k: v for k, v in sorted(
        ex_dict.items(), 
        key=lambda x: list(reversed(list(map(int, x[0].split('/')))))
    )
}

the output

{'3/2019': 1,
 '6/2019': 1,
 '9/2019': 1,
 '3/2020': 1,
 '6/2020': 1,
 '9/2020': 1,
 '3/2021': 1,
 '6/2021': 1}

read details here key-functions

({k: v 
  for k, v in sorted(
      ex_dict.items(),
      key=lambda x: datetime.datetime.strptime(x[0], "%d/%Y")
      )
})

Output:

{'3/2019': 1,
 '6/2019': 1,
 '9/2019': 1,
 '3/2020': 1,
 '6/2020': 1,
 '9/2020': 1,
 '3/2021': 1,
 '6/2021': 1}
  1. datetime.strptime() class method creates a datetime object from a string representing a date and time and a corresponding format string.

  2. Next sorted by date.

see below
(the idea is make a tuple that contains the date as string and a real date, sort it and populate an ordered dict)

from datetime import datetime
from collections import OrderedDict

ex_dict = {
    "6/2021": 1,
    "9/2020": 1,
    "6/2019": 1,
    "3/2020": 1,
    "6/2020": 1,
    "9/2019": 1,
    "3/2021": 1,
    "3/2019": 1,
}

temp = [(datetime(month=int(x[0]), year=int(x[2:]),day=1), x) for x in ex_dict.keys()]
temp = sorted(temp, key=lambda x: x[0])
data = OrderedDict()
for entry in temp:
    data[entry[1]] = ex_dict[entry[1]]
print(data)

output

OrderedDict([('3/2019', 1), ('6/2019', 1), ('9/2019', 1), ('3/2020', 1), ('6/2020', 1), ('9/2020', 1), ('3/2021', 1), ('6/2021', 1)])
Related