-1

This is my data:

k = {'10-06-2021': [1,2,3], '09-06-2021': [2,3,4], '08-06-2021': [5,6,7], '01-06-2021': [8,9,10], '31-05-2021': [11,12,13], '11-06-2021': [14,15,16], '07-06-2021': [17,18,19]}
print(k)

p = sorted(k.items())
print(p)

I want to sorted according to date key and my date format is "dd-mm-yy". when printing data is not comming in order.The issue is sorted function compares data in "yy-mm-dd" format.

I want data to be sorted in ascending date key format. And using sorted() only.

If i write "10-06-2021" as "2021-06-10" result is perfect but this k value is going to db so i don't want to change it.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Pravin Mishra
  • 177
  • 1
  • 9

2 Answers2

0

The key=... parameter in sorted() function will help you here. It basically takes a function or an anonymous lambda function as an argument.

This will be the code for your problem:

k = {'10-06-2021': [1,2,3], '09-06-2021': [2,3,4], '08-06-2021': [5,6,7], '01-06-2021': [8,9,10], '31-05-2021': [11,12,13], '11-06-2021': [14,15,16], '07-06-2021': [17,18,19]}
p = sorted(k.items(), key=lambda x: "".join(reversed(x[0].split("-"))))
print(p)

Explanation

as you said your function works on yyyy-mm-dd format so i converted the string as that format but without '-'. So it sorts according to the format but returns the desired string.

Example:

"12-08-2021" is converted to: "20210812"

Daniyal Shaikh
  • 419
  • 3
  • 12
0

You can also use the datetime module:

  • If you don't need to work with datetimes but may need to include hours in the string in the future:
import datetime
k = {'10-06-2021': [1,2,3], '09-06-2021': [2,3,4], '08-06-2021': [5,6,7], '01-06-2021': [8,9,10], '31-05-2021': [11,12,13], '11-06-2021': [14,15,16], '07-06-2021': [17,18,19]}
p = sorted(k.items(), key=lambda x: datetime.datetime.strptime(x[0], "%d-%m-%Y"))
  • If you want to work with datetime operators:
import datetime
k = {'10-06-2021': [1,2,3], '09-06-2021': [2,3,4], '08-06-2021': [5,6,7], '01-06-2021': [8,9,10], '31-05-2021': [11,12,13], '11-06-2021': [14,15,16], '07-06-2021': [17,18,19]}
# Use datetimes instead of strings in the dictionary
k = {datetime.datetime.strptime(k): v for k, v in k.items()}
p = sorted(k.items(), key=lambda x: x[0])
enzo
  • 9,861
  • 3
  • 15
  • 38