Home > Enterprise >  how to sort a dict by format dates values
how to sort a dict by format dates values

Time:02-01

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

CodePudding user response:

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

CodePudding user response:

Not the best solution out there, here's a very lazy approach:


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

keys  = sorted(data.keys(), reverse=True)#set reverse to True/False depending on what you want 

new_data = {}
for key in keys:
    new_data[key]=data[key]

print(new_data)

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

  • Related