用python对字典排序 [英] Sorting a dictionary in python

查看:66
本文介绍了用python对字典排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
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 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'}

我想拥有

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

提前谢谢!

推荐答案

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

这篇关于用python对字典排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆