开发者

ordering a list of dictionaries by date

I have the following list:

l = [{datetime.d开发者_如何学Pythonate(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])


print sorted(l) 

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

is actually doing the job in this case.

Choosing a more suitable datastructure like a tuple or a dict with explict keys for the date and the value would be of advantage here but as said: working out of the box using sorted().


You should use a list of tuple, or collect those data into a class. Anyway, to get an iterator of keys with the .keys() function, and get any member from it by converting it to an iterable and call next() on it:

l.sort(key=lambda p:next(iter(p.keys())))

If you're using Python 2.x, replace keys with iterkeys.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜