博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python3 中对字典排序
阅读量:4227 次
发布时间:2019-05-26

本文共 1712 字,大约阅读时间需要 5 分钟。

当然,Python3 中的字典 dict 和集合 set 类似,都是没有所谓顺序的,但是你肯定有过这样的需求:怎么让 Python3 中的字典按照键的顺序重新排列得到新的字典呢?下面就给你展示一下吧!

>>> dict_test = {'b': 1, 'a': 2, 'c': 5, 'd': 3}>>> dict(sorted(dict_test.items(), key=lambda x:x[0], reverse=False)){'a': 2, 'b': 1, 'c': 5, 'd': 3}>>> dict(sorted(dict_test.items(), key=lambda x:x[1], reverse=False)){'b': 1, 'a': 2, 'd': 3, 'c': 5}

当然,原来字典中元素的顺序还是保持不变

>>> dict_test{'b': 1, 'a': 2, 'c': 5, 'd': 3}

如果是 python2 的话,dict() 函数与 python3 是稍有差异的(因为 dict() 之后得到的字典本来就应该是没有顺序的,所以在 python2 和 python3 下使用 dict() 函数得到不完全一样的结果也很正常——毕竟反正无所谓顺序,所以以什么样的顺序来显示本来是无关紧要的):

Python 2.7.5 (default, Jun 20 2019, 20:27:34) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> dict_test = {'b': 1, 'a': 2, 'c': 5, 'd': 3}>>> dict(sorted(dict_test.items(), key=lambda x:x[0], reverse=False)){'a': 2, 'c': 5, 'b': 1, 'd': 3}>>> dict_test.items()[('a', 2), ('c', 5), ('b', 1), ('d', 3)]>>> sorted(dict_test.items(), key=lambda x:x[0])[('a', 2), ('b', 1), ('c', 5), ('d', 3)]>>> dict(sorted(dict_test.items(), key=lambda x:x[0])){'a': 2, 'c': 5, 'b': 1, 'd': 3}
Python 3.6.8 (default, Aug  7 2019, 17:28:10) [GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linuxType "help", "copyright", "credits" or "license" for more information.>>> dict_test = {'b': 1, 'a': 2, 'c': 5, 'd': 3}>>> dict(sorted(dict_test.items(), key=lambda x:x[0], reverse=False)){'a': 2, 'b': 1, 'c': 5, 'd': 3}>>> dict_test.items()dict_items([('b', 1), ('a', 2), ('c', 5), ('d', 3)])>>> sorted(dict_test.items(), key=lambda x:x[0], reverse=False)[('a', 2), ('b', 1), ('c', 5), ('d', 3)]>>> dict(sorted(dict_test.items(), key=lambda x:x[0], reverse=False)){'a': 2, 'b': 1, 'c': 5, 'd': 3}

 

转载地址:http://abjqi.baihongyu.com/

你可能感兴趣的文章
SpringMVC+Mybatis+事务回滚+异常封装返回
查看>>
计算机网络实验报告(三):Cisco Packet Tracer 实验
查看>>
嵌入式系统基础学习笔记(九):基于 SPI 协议在 0.96 寸 OLED上【平滑显示汉字】及【温湿度数据采集显示】
查看>>
嵌入式系统基础学习笔记(十):
查看>>
网络通信编程学习笔记(七):Java与MQTT
查看>>
人工智能与机器学习学习笔记(二)
查看>>
Run Your Own Web Server Using Linux & Apache
查看>>
Java I/O
查看>>
SQL Server 2005 T-SQL Recipes: A Problem-Solution Approach
查看>>
Core Python Programming
查看>>
Creating Database Web Applications with PHP and ASP
查看>>
ASP.NET 2.0 Demystified
查看>>
Pattern-Oriented Software Architecture, Volume 2, Patterns for Concurrent and Networked Objects
查看>>
Pattern-Oriented Software Architecture, Volume 1: A System of Patterns
查看>>
Database Programming with Visual Basic® .NET and ADO.NET: Tips, Tutorials, and Code
查看>>
Visual Basic 2005 Express: Now Playing
查看>>
Jakarta Struts Cookbook
查看>>
AspectJ Cookbook
查看>>
IntelliJ IDEA in Action
查看>>
HTML Professional Projects
查看>>