Reputation: 191179
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)?
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','2009/03/10'])} // this comes first as 20 > 10
{'a': (10, ['2010/04/11','2009/03/11'])}
{'c': (100, ['2009/01/01'])}
Upvotes: 1
Views: 1887
Reputation: 3439
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.
Upvotes: 3
Reputation: 799520
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...).
Upvotes: 4