-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.

2
  • 2
    Does this answer your question? sort dates in python array Commented Jun 11, 2021 at 13:59
  • @Tomerikoo no in my case year comes at last. Commented Jun 14, 2021 at 4:28

2 Answers 2

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"

Sign up to request clarification or add additional context in comments.

Comments

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.