我想将 b = {'a':234,'b':1,'c':2,'e':2387} 分别按照key和value进行排序,该怎样办呢?

Python中比较常用的排序有两个函数,

一、定义

(1)一个是List数据结构中的sort

>>> help(list.sort)
Help on method_descriptor:

sort(...)
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) -> -1, 0, 1

  1. The sort() method takes optional arguments for controlling the comparisons.

    cmp specifies a custom comparison function of two arguments (list items) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: cmp=lambda x,y: cmp(x.lower(), y.lower()). The default value is None.

    key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None.

    reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

    In general, the key and reverse conversion processes are much faster than specifying an equivalent cmp function. This is because cmp is called multiple times for each list element while key and reverse touch each element only once. Use functools.cmp_to_key() to convert an old-style cmp function to a key function.

    Changed in version 2.3: Support for None as an equivalent to omitting cmp was added.

    Changed in version 2.4: Support for key and reverse was added.

(2)内置的函数sorted

sorted(iterable[, cmp[, key[, reverse]]])

Return a new sorted list from the items in iterable.

表明内置的sorted函数会生成一个新的数据表不会改变原有数据的顺序。

The optional arguments cmp, key, and reverse have the same meaning as those for the list.sort() method (described in section Mutable Sequence Types).

cmp specifies a custom comparison function of two arguments (iterable elements) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: cmp=lambda x,y: cmp(x.lower(), y.lower()). The default value is None.

key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).

reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

In general, the key and reverse conversion processes are much faster than specifying an equivalent cmp function. This is because cmp is called multiple times for each list element while key and reverse touch each element only once. Use functools.cmp_to_key() to convert an old-style cmp function to a key function.

二、举例

Sorting Basics

>>>sorted([5, 2, 3, 1, 4])
[1, 2, 3, 4, 5]
>>> a = [5, 2, 3, 1, 4]
>>> a.sort()
>>> a
[1, 2, 3, 4, 5] 第一种使用的是内置排序方法,第二种是list的排序方法。Usually it's less convenient than sorted() - but if you don't need the original list, it's slightly more efficient.(虽然第一种方法不是很方便,但是通常更有效率)
>>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})
[1, 2, 3, 4, 5]

Another difference is that the list.sort() method is only defined for lists. In contrast, the sorted() function accepts any iterable.

(另外一点就是list.sort()的方法仅仅只能用作列表的数据结构,然而,sorted却可以用作任何可迭代的数据结构)

Key Functions

Starting with Python 2.4, both list.sort() and sorted() added a key parameter to specify a function to be called on each list element prior to making comparisons(从2.4以后,新添加了key参数,通过制定一个判断函数来按照key进行排序)

>>> sorted("This is a test string from Andrew".split(), key=str.lower)
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
>>> student_tuples = [
('john', 'A', 15),
('jane', 'B', 12),
('dave', 'B', 10),
]
>>> sorted(student_tuples, key=lambda student: student[2]) # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] 关于lambda实际上为匿名函数,后面部分会将 lambda 函数参数:返回值
>>> class Student:
def __init__(self, name, grade, age):
self.name = name
self.grade = grade
self.age = age
def __repr__(self):
return repr((self.name, self.grade, self.age))
def weighted_grade(self):
return 'CBA'.index(self.grade) / float(self.age) >>> student_objects = [
Student('john', 'A', 15),
Student('jane', 'B', 12),
Student('dave', 'B', 10),
]
>>> sorted(student_objects, key=lambda student: student.age) # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

Operator Module Functions

The key-function patterns shown above are very common, so Python provides convenience functions to make accessor functions easier and faster. The operator module has itemgetter, attrgetter, and starting in Python 2.6 a methodcaller function.

Using those functions, the above examples become simpler and faster.

通过引入operator模块有了更快的查询方式:

>>> from operator import itemgetter, attrgetter, methodcaller

>>> sorted(student_tuples, key=itemgetter(2))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] >>> sorted(student_objects, key=attrgetter('age'))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

The operator module functions allow multiple levels of sorting. For example, to sort by grade then by age:

(我们不仅可以按照一种条件进行排序,我们还可以设定多个条件进行排序,如下例中的先按照班级,在按照年龄)

>>> sorted(student_tuples, key=itemgetter(1,2))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)] >>> sorted(student_objects, key=attrgetter('grade', 'age'))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

Ascending and Descending(升降序)

仅仅在后面添加一个reverse就可以了
>>> sorted(student_tuples, key=itemgetter(2), reverse=True)
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] >>> sorted(student_objects, key=attrgetter('age'), reverse=True)
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] 回到刚开始的地方,我们可以很轻松的写出:

import operator
def sortDict():
b = {'a':234,'b':1,'c':2,'e':2387}
print(sorted(b.iteritems(),key=operator.itemgetter(0)))#按key升序排列
print(sorted(b.iteritems(),key=operator.itemgetter(1)))#按value升序排列
print(sorted(b.items(),key=lambda x:x[1],reverse=True))##按value降序排列

输出结果:

[('a', 234), ('b', 1), ('c', 2), ('e', 2387)]
[('b', 1), ('c', 2), ('a', 234), ('e', 2387)]
[('e', 2387), ('a', 234), ('c', 2), ('b', 1)]


 
 
 
 

Python中的字典排序的更多相关文章

  1. python中字典排序,列表中的字典排序

    python中字典排序,列表中的字典排序 一.使用python模块:operator import operator #首先要导入模块operator x = {1:2, 3:4, 4:3, 2:1, ...

  2. 如何将xml转为python中的字典

    如何将xml转为python中的字典 import cElementTree as ElementTree class XmlListConfig(list): def __init__(self, ...

  3. Python中的字典与集合

    今天我们来讲一讲python中的字典与集合 Dictionary:字典 Set:集合 字典的语法: Dictionary字典(键值对) 语法: dictionary = {key:value,key: ...

  4. Python中对列表排序实例

    Python中对列表排序实例 发布时间:2015-01-04 09:01:50 投稿:junjie 这篇文章主要介绍了Python中对列表排序实例,本文给出了9个List的排序实例,需要的朋友可以参考 ...

  5. python中的字典(dict),列表(list),元组(tuple)

    一,List:列表 python内置的一种数据类型是列表:list.list是一种有序的数据集合,可以随意的添加和删除其中的数据.比如列出班里所有的同学的名字,列出所有工厂员工的工号等都是可以用到列表 ...

  6. Python中数据的排序

    目录 列表的排序 sort(key,reverse)方法 sorted(target,key,reverse) 函数 元组tuple的排序 sort(key,reverse)方法 sorted(tar ...

  7. 漫谈python中的搜索/排序

    在数据结构那一块,搜索有顺序查找/二分查找/hash查找,而排序有冒泡排序/选择排序/插入排序/归并排序/快速排序.如果遇到数据量和数组排列方式不同,基于时间复杂度的考虑,可能需要用到混合算法.如果用 ...

  8. 13.python中的字典

    字典其实和之前的元祖和列表功能相似,都是用来储存一系列对象的.也就是一种可变容器,或者是我所比喻的革新派的菜单. 但也不是完全相同,我在之前曾经将字典称为特殊的'序列',是字典拥有序列的部分特性,但是 ...

  9. iOS开发——NSArray中的字典排序

    手头上碰到一个项目,需要给数组中的字典中的一个字段排序,想了想,干脆再字典中增加一个字段,用来记录需要排序字段的第一个字符,用它来作为比较的对象,进行排序. - (void)viewDidLoad { ...

随机推荐

  1. git注意

    .ssh生成的公钥全部复制然后粘贴到gitHub上,公钥是放在.ssh文件夹里面的,复制前先找到这个文件夹 提示出错信息:fatal: remote origin already exists. 解决 ...

  2. 20151009 C# 第一篇 程序编写规范

    20151009 程序编写规范 1. 代码书写规则: 1).尽量使用接口,然后使用类实现接口. 2).关键语句写注释 3).避免写超过5个参数的方法,如果要传递多个参数,则使用结构 4).避免代码量过 ...

  3. 写在Ruby之前。

    jeiao: 入行程序员也有一年的时间,入门的时候学的Java,在公司写了大半年的Java,也主要是Web方向,使用过struts2 做过项目,后来又用SSH实现了一遍,感觉就那么点意思,因为公司规模 ...

  4. 占位符(placeholder text)

    占位符(placeholder text)是用户在input(输入)框输入任何东西之前放置在input(输入)框中的预定义文本. 你可以用如下方式创建占位符: <input type=" ...

  5. 对IEnumerable<T>和IQueryable<T>的一点见解

    今天学习了用EF模型做查询,感觉数据库上下文对象的扩展方法很强大,所以研究了一下where的实现原理,其中遇到了一个问题,就是关于IEnumerable和IQueryable的区别,所以查了查资料,这 ...

  6. OpenGL(四)——有用的函数

    概述 1. reshape 定义窗口和图像的映射关系,使在不以纵横比4:3调整窗口大小时,图像不会失真 函数 1. ReShape 如果变更后的窗体的横纵比大于4/3,需要以高为基数,宽为高*4/3, ...

  7. Webpack使用教程五(Babel)

    Babel是一个JavaScript编译和工具平台,使用Babel我们可以:使用新版本的JavaScript(ES6/ES2015,ES7/ES2016),尽管有些浏览器不能全部支持新特性:使用Jav ...

  8. Jeasyframe 开源框架 稳定版 V1.5 发布

    这是Jeasyframe开源框架的第一个稳定版本,感谢一起帮忙测试并给予反馈的网友们. 框架官网:http://www.jeasyframe.org/ 产品介绍: Jeasyframe开源框架是基于S ...

  9. 在Debian下编译Postgresql

    今天起床看到床头上的那本<PostgreSQL数据库内核分析>,发觉这书买了这么长时间,虽然大致看了一遍,可还没亲手实践.今天就花了点时间搭了个调试环境. 环境:Debian 7.0 ## ...

  10. OS——进程简答题(1)

    1,叙述进程和程序的主要区别. 解:进程和程序是两个既有联系又有区别的两个概念,它们的主要区别如下: (1)程序是指令的有序集合,其本身没有任何运行的含义,它是一个静态的概念.而进程是程序在处理机上的 ...