0

I got a dict of names as keys and formated dates as values, I managed to have the list of these dates sorted, but I dont know how to now sort my dict with this "custom order", since the dates are weirdly formated, sort() won't work.

Here is an example :

dict = {'Charles':'01/02-21:00','Martin':'01/03-22:00','David':'01/02-19:00'}

The dates are formated as day/month-hour:minute.

The sorted list of dates would be ['01/02-19:00','01/02-21:00','01/03-22:00']

And the wanted dict output {'David':'01/02-19:00','Charles':'01/02-21:00','Martin':'01/03-22:00'}

1
  • "sort() won't work' - Doesn't even exist. Commented Feb 1, 2023 at 10:40

1 Answer 1

2

Use:

>>> import time
>>>
>>>
>>> d = {"Charles": "01/02-21:00", "Martin": "01/03-22:00", "David": "01/02-19:00"}
>>>
>>> dict(sorted(d.items(), key=lambda arg: time.strptime(arg[1], "%d/%m-%H:%M")))
{'David': '01/02-19:00', 'Charles': '01/02-21:00', 'Martin': '01/03-22:00'}

As a generic piece of advice, try choosing for your identifiers names that aren't already used, as you will shadow previous definitions (in your case: [Python.Docs]: Built-in Functions - class dict(**kwarg)).

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

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.