flair
flair

Reputation: 21

how to sort a dict by format dates values

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'}

Upvotes: 0

Views: 48

Answers (1)

CristiFati
CristiFati

Reputation: 41116

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

Upvotes: 2

Related Questions