开发者

Sorting nested python dictionary

I have a python dictionary with the following format.

{'KEY': (NUMBER, [DATE1, DATE2]}

For example, {'a': (10, ['2010/04/11','2009/03/11'])}

How can I sort this dictionary by the DATE1(the first element in the list)?

EDIT

Can I sorted again when the date is the same? For example.

{'a': (10, ['2010/04/11','2009/03/11'])}
{'b': (20, ['2010/04/11','2009/03/10'])}
{'c': (100, ['2009/01/01'])}

-->

{'b': (20, ['2010/04/11开发者_StackOverflow社区','2009/03/10'])} // this comes first as 20 > 10
{'a': (10, ['2010/04/11','2009/03/11'])}
{'c': (100, ['2009/01/01'])}


Dictionaries are unsortable. If you want a sorted list of 2-tuples:

sorted(D.iteritems(), key=lambda x: x[1][1][0])

Pass the expression to datetime.strptime() if you want it in date order instead of string order (not that there is a huge difference given the existing date format...).


If you're using Python 2.7 or later, you can use the new collections.OrderedDict class. Along with Ignacio's code for doing the actual sorting, that should give you what you're looking for.

Say that a is your current dictionary, then

OrderedDict(sorted(a.items(), key=lambda x: (x[1][1][0], -x[1][0])))

will return a sorted version.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜