如何按键对字典进行排序?
示例输入:
{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}
当前回答
在Python 3中。
>>> D1 = {2:3, 1:89, 4:5, 3:0}
>>> for key in sorted(D1):
print (key, D1[key])
给了
1 89
2 3
3 0
4 5
其他回答
有许多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])
找到了另一种方法:
import json
print json.dumps(d, sort_keys = True)
乌利希期刊指南: 1. 这也可以对嵌套对象进行排序(谢谢@DanielF)。 2. Python字典是无序的,因此只适用于打印或赋值给STR。
来自Python的集合库文档:
>>> from collections import OrderedDict
>>> # regular unsorted dictionary
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
>>> # dictionary sorted by key -- OrderedDict(sorted(d.items()) also works
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
>>> # dictionary sorted by value
>>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])
>>> # dictionary sorted by length of the key string
>>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])
会产生你想要的结果:
D1 = {2:3, 1:89, 4:5, 3:0}
sort_dic = {}
for i in sorted(D1):
sort_dic.update({i:D1[i]})
print sort_dic
{1: 89, 2: 3, 3: 0, 4: 5}
但这并不是正确的方法,因为它可以在不同的字典中显示不同的行为,这是我最近学到的。因此,蒂姆在回答我的问题时提出了一个完美的方法,我在这里分享。
from collections import OrderedDict
sorted_dict = OrderedDict(sorted(D1.items(), key=lambda t: t[0]))
有一种简单的方法来整理字典。
根据你的问题,
解决方案是:
c={2:3, 1:89, 4:5, 3:0}
y=sorted(c.items())
print y
(其中c是你的字典名。)
这个程序给出如下输出:
[(1, 89), (2, 3), (3, 0), (4, 5)]
如你所愿。
另一个例子是:
d={"John":36,"Lucy":24,"Albert":32,"Peter":18,"Bill":41}
x=sorted(d.keys())
print x
给出输出:['Albert', 'Bill', 'John', 'Lucy', 'Peter']
y=sorted(d.values())
print y
给出输出:[18,24,32,36,41]
z=sorted(d.items())
print z
给出输出:
[('Albert', 32), ('Bill', 41), ('John', 36), ('Lucy', 24), ('Peter', 18)]
因此,通过将其更改为键、值和项,您可以像您想要的那样打印。希望这能有所帮助!