如何按键对字典进行排序?
示例输入:
{2:3, 1:89, 4:5, 3:0}
期望的输出:
{1:89, 2:3, 3:0, 4:5}
如何按键对字典进行排序?
示例输入:
{2:3, 1:89, 4:5, 3:0}
期望的输出:
{1:89, 2:3, 3:0, 4:5}
当前回答
此函数将根据键对任何字典进行递归排序。也就是说,如果字典中的任何值也是一个字典,它也将根据它的键进行排序。如果您运行在CPython 3.6或更高版本上,则可以简单地更改为使用dict而不是OrderedDict。
from collections import OrderedDict
def sort_dict(d):
items = [[k, v] for k, v in sorted(d.items(), key=lambda x: x[0])]
for item in items:
if isinstance(item[1], dict):
item[1] = sort_dict(item[1])
return OrderedDict(items)
#return dict(items)
其他回答
有许多Python模块提供字典实现,这些字典自动按排序顺序维护键。考虑sortedcontainers模块,它是纯python和像c一样快的实现。此外,还会与其他受欢迎的选项进行性能比较。
如果您需要在迭代的同时不断地添加和删除键/值对,那么使用有序字典是一个不合适的解决方案。
>>> from sortedcontainers import SortedDict
>>> d = {2:3, 1:89, 4:5, 3:0}
>>> s = SortedDict(d)
>>> s.items()
[(1, 89), (2, 3), (3, 0), (4, 5)]
SortedDict类型还支持索引位置查找和删除,这在内置dict类型中是不可能的。
>>> s.iloc[-1]
4
>>> del s.iloc[2]
>>> s.keys()
SortedSet([1, 2, 4])
注意:对于Python 3.7+,请参见此答案
标准Python字典是无序的(直到Python 3.7)。即使对(键,值)对进行了排序,也不能将它们存储在字典中以保持排序。
最简单的方法是使用OrderedDict,它会记住元素被插入的顺序:
In [1]: import collections
In [2]: d = {2:3, 1:89, 4:5, 3:0}
In [3]: od = collections.OrderedDict(sorted(d.items()))
In [4]: od
Out[4]: OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)])
不要在意od是如何打印出来的;它会像预期的那样工作:
In [11]: od[1]
Out[11]: 89
In [12]: od[3]
Out[12]: 0
In [13]: for k, v in od.iteritems(): print k, v
....:
1 89
2 3
3 0
4 5
Python 3
对于Python 3用户,需要使用.items()而不是.iteritems():
In [13]: for k, v in od.items(): print(k, v)
....:
1 89
2 3
3 0
4 5
您可以根据您的问题按键对当前字典进行排序,从而创建一个新字典。
这是你的字典
d = {2:3, 1:89, 4:5, 3:0}
通过使用lambda函数对这个d排序,创建一个新字典d1
d1 = dict(sorted(d.items(), key = lambda x:x[0]))
D1应为{1:89,2:3,3:0,4:5},根据d中的键进行排序。
Python字典在Python 3.6之前是无序的。在Python 3.6的CPython实现中,字典保持插入顺序。 从Python 3.7开始,这将成为一种语言特性。
在Python 3.6的更新日志(https://docs.python.org/3.6/whatsnew/3.6.html#whatsnew36-compactdict):
考虑了这个新实现的保序方面 一个实现细节,不应该依赖(这可能 将来会有变化,但希望有这个新词典 在语言中实现了几个版本,然后才更改 语言规范要求所有当前的语义保持有序 以及未来的Python实现;这也有助于保存 向后兼容该语言的旧版本 随机迭代顺序仍然有效,例如Python 3.5)。
Python 3.7文档(https://docs.python.org/3.7/tutorial/datastructures.html#dictionaries):
在字典上执行list(d)将返回所有使用的键的列表 在字典中,按插入顺序(如果你想排序,只需使用 排序(d))。
因此,与以前的版本不同,您可以在Python 3.6/3.7之后对字典进行排序。如果你想对包含子字典在内的嵌套字典进行排序,你可以这样做:
test_dict = {'a': 1, 'c': 3, 'b': {'b2': 2, 'b1': 1}}
def dict_reorder(item):
return {k: dict_reoder(v) if isinstance(v, dict) else v for k, v in sorted(item.items())}
reordered_dict = dict_reorder(test_dict)
https://gist.github.com/ligyxy/f60f0374defc383aa098d44cfbd318eb
正如其他人所提到的,字典本质上是无序的。然而,如果问题只是以有序的方式显示字典,你可以在字典子类中重写__str__方法,并使用这个字典类而不是内置的字典。如。
class SortedDisplayDict(dict):
def __str__(self):
return "{" + ", ".join("%r: %r" % (key, self[key]) for key in sorted(self)) + "}"
>>> d = SortedDisplayDict({2:3, 1:89, 4:5, 3:0})
>>> d
{1: 89, 2: 3, 3: 0, 4: 5}
注意,这不会改变键的存储方式,当你遍历它们时它们返回的顺序等,只是它们在打印时或在python控制台中显示的方式。