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.
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With