本文共 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/