2

Possible Duplicate:
Python: Sort a dictionary by value

I need to sort by values a original dictionary on a descending order.
As keys I have numbers and as values I have some date and time (string).

This means I have:

{1: '2011-09-25 16:28:18', 2: '2011-09-25 16:28:19', 3: '2011-09-25 16:28:13', 4: '2011-09-25 16:28:25'}

And I want to have:

{4: '2011-09-25 16:28:25', 2: '2011-09-25 16:28:19', 1: '2011-09-25 16:28:18', 3: '2011-09-25 16:28:13'}

Please, look at the times (value). I want to sort the times on a descending order. This means, the most recent time first.

Thanks in advance!

Community
  • 1
  • 1
user963658
  • 151
  • 1
  • 2
  • 9

2 Answers2

3
import operator
x = { 1: '2011-09-25 16:28:18',
      2: '2011-09-25 16:28:19',
      3: '2011-09-25 16:28:13',
      4: '2011-09-25 16:28:25',
      }
sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1), reverse=True)

print(sorted_x)

This results in a list of (key, value) tuples:

[(4, '2011-09-25 16:28:25'),
 (2, '2011-09-25 16:28:19'),
 (1, '2011-09-25 16:28:18'),
 (3, '2011-09-25 16:28:13')]
Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
garnertb
  • 9,454
  • 36
  • 38
2

Python builtin dict dictionaries aren't ordered, so you cannot do that, you need a different container.

With Python 3.1 or 2.7 you can use collections.OrderedDict. For earlier version see this recipe.

mmmmmm
  • 32,227
  • 27
  • 88
  • 117
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
  • Well, but I can take this dictionary and order it by putting it on a new dictionary or something? This would be a great method. I dont care using a different container. I just dont know how to do it :/ – user963658 Sep 25 '11 at 14:40
  • OrderedDict is ordered on keys not values. You need to explicitly sort it by value – David Heffernan Sep 25 '11 at 14:41
  • Ordered != sorted. One can use the orderedness to make it sorted, but maintaining this in moderately complex. If you just need (key, value) pairs in sorted (regardless on what) order once in a while, it may be easier to just use `sorted` and `.iteritems`. –  Sep 25 '11 at 14:45
  • @David: there is an example for that in the linked manual. but he still didn't tell use whether is python 2 or 3.. – Karoly Horvath Sep 25 '11 at 14:45