1

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','2009/03/10'])} // this comes first as 20 > 10
{'a': (10, ['2010/04/11','2009/03/11'])}
{'c': (100, ['2009/01/01'])}
1
  • What do you mean by saying sort this dictionary? Do you have a lot of dictionaries in this format? Commented Mar 15, 2011 at 4:20

2 Answers 2

4

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...).

Sign up to request clarification or add additional context in comments.

3 Comments

It's worth mentioning that the reason dictionaries are unsortable is that they don't maintain any notion of an ordering of their elements.
I added one more question. Can I sort in the sorted list when the date is the same? Thanks.
Sure. Just return a tuple as the key. key=lambda x: (x[1][1][0], -x[1][0])
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.