优草派  >   Python

Python中itemgetter函数如何实现字典排序? itemgetter函数实现字典排序的方法

翟嘉慧            来源:优草派

对于字典的排序上,在前面的文章中已经学过了不少的方法,今天的这篇文章中要介绍的是operator 模块中Itemgetter函数的方法。它可以就字典中的某个字段进行排序,最后我们得到的结果也更加有针对性。下面一起来看看这篇文章吧。

Python中itemgetter函数如何实现字典排序? itemgetter函数实现字典排序的方法

一、Itemgetter函数的概念

在Python中,对字典的排序方式有很多种,使用Itemgetter函数操作也可以实现字典的排序,它的主要功能就是将一个对象的位置数据进行获取,在函数中的参数就是代表这个位置的序号值,因为这个函数是存在operator 模块中的,所以我们在使用这个函数之前,需要将模块导入进来,导入方法如下:

from operator import itemgetter
或
import operator

二、注意事项

因为在这个函数中,获取到的并不是一个具体的值,而是对函数进行了定义,只有它通过这个函数才能找到对象中的值。

三、函数的应用

下面通过使用operator模块中的 itemgetter函数,简单的对数据结构进行排序,代码如下:

from operator import itemgetter
hhrows = sorted(rows, key=itemgetter('fname'))
hhrows

运行结果:

[{'fname': 'Wang', 'lname': 'Hu', 'uid': 1004},
 {'fname': 'Huang', 'lname': 'Hu', 'uid': 1003},
 {'fname': 'Peng', 'lname': 'Zhai', 'uid': 1002},
 {'fname': 'Wu', 'lname': 'Cleese', 'uid': 1001}]

运行结果:

rows_by_uid = sorted(rows, key=itemgetter('uid'))
[{'fname': 'Wu', 'lname': 'Cleese', 'uid': 1001},
 {'fname': 'Peng', 'lname': 'Zhai', 'uid': 1002},
 {'fname': 'Huang', 'lname': 'Hu', 'uid': 1003},
 {'fname': 'Wang', 'lname': 'Hu', 'uid': 1004}]

关于“Python中itemgetter函数如何实现字典排序? itemgetter函数实现字典排序的方法”的内容就讲解到这里了,希望大家通过对这篇文章的学习能掌握好Python使用temgetter函数实现字典排序的操作。

【原创声明】凡注明“来源:优草派”的文章,系本站原创,任何单位或个人未经本站书面授权不得转载、链接、转贴或以其他方式复制发表。否则,本站将依法追究其法律责任。