Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ordering a list of dictionaries by date

I have the following list:

l = [{datetime.date(2011, 4, 30): "Carrot"}, 
     {datetime.date(2009, 4, 12): "Banana"},
     {datetime.date(2012, 1, 1): "Corn"}]

I want a new list with the dictionaries ordered by date (earliest first):

l = [{datetime.date(2009, 4, 12): "Banana"},
     {datetime.date(2011, 4, 30): "Carrot"},
     {datetime.date(2012, 1, 1): "Corn"}]

I expect the answer involves sorted and key but I'm struggling to isolate the key of each dictionary to use as the comparator. In other questions which have posed a similar problem, the dictionaries take the form:

{'date':datetime.date(2009, 4, 12): "Banana"} 

The addition of the date string seems to make the task easier but i'd like to avoid it if possible

cheers.

like image 540
Paul Patterson Avatar asked Dec 08 '25 12:12

Paul Patterson


1 Answers

Use the key of your inner dictionary as sort key. You can do this by passing a key getter function to sorted which pulls out the date key from your dictionary.

sorted(l, key=lambda v: v.keys()[0])
like image 200
Imran Avatar answered Dec 10 '25 02:12

Imran