Skip to content Skip to sidebar Skip to footer

Sorting A Dictionary In Python

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 dat

Solution 1:

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')]

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

Post a Comment for "Sorting A Dictionary In Python"