在Python中排序字典

可能重复:
Python:按值排序字典

我需要按降序对原始字典进行排序。
作为我有数字和我有一些日期和时间(字符串)。

这意味着我有:

{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'}

我想要:

{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'}

请看,时间(价值)。 我想按降序排列时间。 这意味着,最近的时间在先。

提前致谢!


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)

这导致(键,值)元组列表:

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

Python的内建dict字典是没有顺序的,所以你不能做到这一点,你需要一个不同的容器。

使用Python 3.1或2.7,你可以使用collections.OrderedDict。 对于早期版本,请参阅此配方。

链接地址: http://www.djcxy.com/p/18163.html

上一篇: Sorting a dictionary in python

下一篇: How to use the dictionary function?