python 多关键字排序

介绍 (Introduction)

In this tutorial, we are going to take a look at the various ways following which we can Sort a Dictionary in Python.

在本教程中,我们将研究可以用Python排序字​​典的各种方式。

In Python, a Dictionary is a collection of key-value pairs. The sequence of such key and value pairs is separated by commas. These pairs are called items.

在Python中, 字典是键值对的集合。 这样的对的顺序以逗号分隔。 这些对称为

用Python对字典进行排序的不同方法 (Different Ways to sort a Dictionary in Python)

As mentioned above, a dictionary item consists of a key and its corresponding value. Hence, sorting for a dictionary can be performed by using any one of the key or value parts as a parameter.

如上所述,字典项由键及其对应的值组成。 因此,可以通过使用部分中的任何一个作为参数来执行字典的排序。

So, let us now take a look at the different methods by which we can sort a dictionary by key or by value.

因此,现在让我们看一下可以通过键对字典进行排序的不同方法。

1.按关键字排序字典 (1. Sort Dictionary by Key)

We can directly sort a dictionary using the built-in sorted() method in Python. This can be done by passing the dictionary itself and a function that specifies the parameter on the basis of which the sorting is to be done(in this case key).

我们可以使用Python中内置的sorted()方法直接对字典进行sorted() 。 这可以通过传递字典本身和一个函数来完成,该函数指定要基于其进行排序的参数(在本例中为键)。

Let us see how.

让我们看看如何。


d = { 5: 1 , 4: 2 , 3: 3 , 2: 4 , 1: 5 }print("The original dictionary: ", d)#sorting by key
a = dict(sorted(d.items(), key=lambda x: x[0]))print("After sorting by key: ", a)

Output:

输出:


The original dictionary:  {5: 1, 4: 2, 3: 3, 2: 4, 1: 5}
After sorting by key:  {1: 5, 2: 4, 3: 3, 4: 2, 5: 1}

Here,

这里,

  • The d.items() method returns a list of tuples(items) containing the keys and their corresponding values,d.items()方法返回一个元组(items)列表,其中包含及其对应的
  • The lambda function returns the key(0th element) for a specific item tuple,lambda函数返回特定项目元组的key( 第0个元素),
  • When these are passed to the sorted() method, it returns a sorted sequence which is then type-casted into a dictionary.当这些参数传递给sorted()方法时,它返回排序的序列,然后将其类型转换为字典。

Remember, this method can be used in Python 3.6+ versions as it considers dictionaries as ordered sequences. For older versions, we can replace the lambda function with the itemgetter() method from the operator module. Let us see how.

请记住,此方法可在Python 3.6+版本中使用,因为它将字典视为有序序列。 对于较旧的版本,我们可以使用operator模块中的itemgetter()方法替换lambda函数。 让我们看看如何。


from operator import itemgetterd = { 5: 1 , 4: 2 , 3: 3 , 2: 4 , 1: 5 }
print("Original Dict: ", d)#sorting by key
s_d = dict(sorted(d.items(), key=itemgetter(0)))
print("Sorted dict: ", s_d)

Output:

输出:


Original Dict:  {5: 1, 4: 2, 3: 3, 2: 4, 1: 5}
Sorted dict:  {1: 5, 2: 4, 3: 3, 4: 2, 5: 1}

Here also the methods sorted() and items() work the same way. But in place of a lambda function, the itemgetter(0) method returns a callable object that fetches the 0th item from its operand using the operand’s __getitem__() method. In this case, as we need to sort by key, we consider the 0th element.

这里的sorted()items()方法也以相同的方式工作。 但是代替lambda函数, itemgetter(0)方法返回一个可调用对象,该对象使用操作数的__getitem__()方法从其操作数中获取第0个项目。 在这种情况下,由于我们需要按key排序,因此我们考虑第0个元素。

2.按值对字典排序 (2. Sort a Dictionary by Value)

Sorting a dictionary by value is similar to sorting by key. The only difference being that this type the parameter on the basis of which the sorting would be done is the value part of the corresponding items.

按值对字典进行排序类似于按键对字典进行排序。 唯一的不同是,此类型的参数将根据其进行排序,而该参数是相应项目的部分。

Hence as we did earlier, we can use the sorted() method along with a lambda function for Python 3.6+ versions. Let us see how.

因此,就像我们之前所做的那样,对于Python 3.6+版本,我们可以将sorted()方法与lambda函数一起使用。 让我们看看如何。


d = { 0: 'd', 1: 'c', 2: 'b', 3: 'a' }print("The original dictionary: ", d)#sorting by value
a = dict(sorted(d.items(), key=lambda x: x[1]) )print("After sorting by value: ", a)

Output:

输出:


The original dictionary:  {0: 'd', 1: 'c', 2: 'b', 3: 'a'}
After sorting by value:  {3: 'a', 2: 'b', 1: 'c', 0: 'd'}

Similarly here, according to the values returned by the lambda function(x[1] value for an item x) the dictionary d is sorted.

同样在这里,根据由lambda函数(返回的值x[1]值的项目x )的字典d排序。

Again for older versions of Python follow the below-mentioned method.

同样,对于旧版本的Python,请遵循以下方法。


from operator import itemgetterd = { 0: 'd', 1: 'c', 2: 'b' , 3: 'a' }
print("Original Dict: ", d)#sorting by value
s_d = dict(sorted(d.items(), key=itemgetter(1)))
print("Sorted dict: ", s_d)

Output:

输出:


Original Dict:  {0: 'd', 1: 'c', 2: 'b', 3: 'a'}
Sorted dict:  {3: 'a', 2: 'b', 1: 'c', 0: 'd'}

Similarly, sorted() along with d.items() and itemgetter(1) methods sort the dictionary d on the basis of value.

类似地,sorted()连同d.items()和itemgetter(1)方法根据值对字典d进行排序。

3.反向排序 (3. Sorting in reverse order)

The sorted() method comes with another argument reverse. That can be used for specifying the order in which the sorting is to be done. If passed True, the sorting takes place in reverse order(descending). And if False is passed(default), the sorting takes place in ascending order.

sorted()方法带有另一个参数reverse 。 可以用于指定排序的顺序。 如果通过True ,则排序以相反的顺序(降序)进行。 如果传递了False (默认值),则排序以升序进行

Let us try to understand this by an example where we try to reverse sort a dictionary by key.

让我们尝试通过一个示例对这种情况进行理解,在该示例中,我们尝试对关键字进行反向排序。


d = { 'a': 23, 'g': 67, 'e': 12, 45: 90}print("The original dictionary: ", d)#sorting by value in reverse
a = dict(sorted(d.items(), reverse = True, key=lambda x: x[1]))
print("After sorting by value in reverse order: ", a)#sorting by value in ascending order
a = dict(sorted(d.items(), key=lambda x: x[1]))#by default reverse is set to False
print("After sorting by value in ascending order: ", a)

Output:

输出:


The original dictionary:  {'a': 23, 'g': 67, 'e': 12, 45: 90}
After sorting by value in reverse order:  {45: 90, 'g': 67, 'a': 23, 'e': 12}
After sorting by value in ascending order:  {'e': 12, 'a': 23, 'g': 67, 45: 90}

From the above output, it is clear that passing the reverse parameter as True the above dictionary is sorted in reverse order(descending).

根据以上输出, 显然,将反向字典作为True传递给上面的字典是按相反的顺序排序( 降序 )。

结论 (Conclusion)

So in this tutorial, we learned how we can sort a dictionary in Python using various methods.

因此,在本教程中,我们学习了如何使用各种方法在Python中对字典进行排序

For any further questions, feel free to use the comments below.

如有其他疑问,请随时使用以下评论。

参考资料 (References)

  • How to Sort a Dictionary in Python? – AskPython Post如何在Python中对字典排序? – AskPython发布
  • Python Dictionary – Journal Dev PostPython字典 – Journal Dev Post
  • How do I sort a dictionary by value? – Stackoverflow Question如何按值对字典排序? – Stackoverflow问题
  • How can I sort a dictionary by key? – Stackoverflow Question如何按键对字典排序? – Stackoverflow问题

翻译自: https://www.journaldev.com/38407/sort-a-dictionary-in-python

python 多关键字排序

python 多关键字排序_用Python排序字​​典相关推荐

  1. python中用def实现自动排序_用 python 实现各种排序算法

    常见集中排序的算法 归并排序 归并排序也称合并排序,是分治法的典型应用.分治思想是将每个问题分解成个个小问题,将每个小问题解决,然后合并. 具体的归并排序就是,将一组无序数按n/2递归分解成只有一个元 ...

  2. python将对象放入列表根据某个属性排序_关于python:如何根据对象的属性对对象列表进行排序?...

    我有一个python对象列表,我想按对象本身的属性排序.列表如下: >>> ut [, , , , , , ...] 每个对象都有一个计数: >>> ut[1].c ...

  3. python优先级排序_用Python实现优先级队列的3种方法

    微信公众号:冰咖啡与狗 1. 什么是优先级队列? 优先级队列是一种容器型数据结构,它能管理一队记录,并按照排序字段(例如一个数字类型的权重值)为其排序.由于是排序的,所以在优先级队列中你可以快速获取到 ...

  4. 希尔排序python 简书_数据结构_排序_直接插入+希尔排序

    数据结构_排序_直接插入排序+希尔排序 其实主要是为了讲述希尔排序,不过插入排序是希尔排序的基础,因此先来讲直接插入排序. 一.直接插入排序 1.原理 下标 0 1 2 3 4 5 6 7 8 -- ...

  5. python中级项目下载_中级Python复习:教程,项目思想和技巧

    python中级项目下载 本文旨在向Python初学者和开发人员介绍Python中使用的一些关键概念,这些概念一开始就没有讲授. 如果您可以创建二次方根求解器,则可以理解本文. 这些是我一天之内没有学 ...

  6. python画交互式地图_使用Python构建交互式地图-入门指南

    python画交互式地图 Welcome to The Beginner's Guide to Building Interactive Maps in Python 欢迎使用Python构建交互式地 ...

  7. 以下选项中python用于异常处理结构_《Python 程序设计》复习题

    目录 填空题 一.基础知识 二.序列 三.选择结构与循环结构和函数及面向对象.文件 选择题 一.Python 基础语法 二.基本数据类型 三.程序的控制结构 四.函数和代码复用 五.组合数据类型 六. ...

  8. python 科学计算设计_《Python科学计算-(第2版)》怎么样_目录_pdf在线阅读 - 课课家教育...

    第1章 Python科学计算环境的安装与简介 1 1.1 Python简介 1 1.1.1 Python 2还是Python 3 1 1.1.2 开发环境 2 1.1.3 集成开发环境(IDE) 5 ...

  9. python大牛 关东升_《Python从小白到大牛》第4章 Python语法基础

    本章主要为大家介绍Python的一些语法,其中包括标识符.关键字.常量.变量.表达式.语句.注释.模块和包等内容. 标识符和关键字 任何一种计算机语言都离不开标识符和关键字,因此下面将详细介绍Pyth ...

最新文章

  1. eoiioe IE 和 firefox js 兼容问题
  2. 上小学的读者居然造了个“编程语言”!
  3. spring cloud集成 consul源码分析
  4. 绝不能错过的10款最新OpenStack网络运维 监控工具
  5. 网络传输为什么要序列化_企业为什么要选择网络营销外包
  6. 你抢的不是春节红包而是云
  7. 代码编辑器sublime text 4使用小技巧--快捷键说明
  8. python分割合并文件
  9. 摄影测量--共线方程
  10. bat计算机清理原理,电脑如何一键清除垃圾bat
  11. ps——投影字体效果
  12. 一封谷歌账号辅助邮箱变更的广告邮件
  13. 【jQWidgets】jqxGrid控件在页面上重新加载的问题
  14. 你有你的计划,世界另有计划这本书 万维钢
  15. 物联卡先用流量包还是套餐流量,物联卡流量扣除顺序是什么?
  16. 什么是短网址?如何调用接口生成短地址?
  17. Java序列化三连问,是什么?为什么需要?如何实现?
  18. 微信第 1 行代码曝光!
  19. mysql source导入大数据量时效率提升的方法
  20. 【sfu】network线程和主线程

热门文章

  1. UVA455 - Periodic Strings(周期串)
  2. 主题切换时如何主动去刷新一些资源?
  3. Android ADV 虚拟卡常见错误Failed to push的解决
  4. lightbox的一个ajax效果
  5. [转载] numpy逆 python_Python之Numpy详细教程,附Python最新学习资料
  6. [转载] Python Web开发—进阶提升 490集超强Python视频教程 真正零基础学习Python视频教程
  7. [转载] Java异常:选择Checked Exception还是Unchecked Exception?
  8. [Bzoj1010][HNOI2008]玩具装箱toy(斜率优化)
  9. oracle 查看最大连接数与当前连接数
  10. linux使用tar命令打包压缩时排除某个文件夹或文件