如何按键对字典进行排序?

示例输入:

{2:3, 1:89, 4:5, 3:0}

期望的输出:

{1:89, 2:3, 3:0, 4:5}

当前回答

就问题的表述方式而言,这里的大多数答案都是正确的。

然而,考虑到事情应该如何真正完成,考虑到几十年的计算机科学,让我完全惊讶的是,这里实际上只有一个答案(来自GrantJ用户)建议使用排序关联容器(sortedcontainers),它基于插入点的键对元素进行排序。

这将避免每次调用sort(…)时对性能的巨大影响(至少O(N*log(N)),其中N是元素的数量(逻辑上,这适用于这里建议使用sort(…)的所有此类解决方案)。考虑到对于所有这样的解决方案,sort(…)将需要在每次通过添加/删除元素修改后,当需要以排序方式访问集合时调用…

其他回答

我认为最简单的事情是按键对字典进行排序,并将排序的键:值对保存在一个新的字典中。

dict1 = {'renault': 3, 'ford':4, 'volvo': 1, 'toyota': 2} 
dict2 = {}                  # create an empty dict to store the sorted values
for key in sorted(dict1.keys()):
    if not key in dict2:    # Depending on the goal, this line may not be neccessary
        dict2[key] = dict1[key]

更清楚地说:

dict1 = {'renault': 3, 'ford':4, 'volvo': 1, 'toyota': 2} 
dict2 = {}                  # create an empty dict to store the sorted     values
for key in sorted(dict1.keys()):
    if not key in dict2:    # Depending on the goal, this line may not be  neccessary
        value = dict1[key]
        dict2[key] = value

在这里,我找到了一些最简单的解决方案,使用pprint按键对python字典进行排序。 如。

>>> x = {'a': 10, 'cd': 20, 'b': 30, 'az': 99} 
>>> print x
{'a': 10, 'b': 30, 'az': 99, 'cd': 20}

但是当使用pprint时,它将返回排序后的dict

>>> import pprint 
>>> pprint.pprint(x)
{'a': 10, 'az': 99, 'b': 30, 'cd': 20}

就问题的表述方式而言,这里的大多数答案都是正确的。

然而,考虑到事情应该如何真正完成,考虑到几十年的计算机科学,让我完全惊讶的是,这里实际上只有一个答案(来自GrantJ用户)建议使用排序关联容器(sortedcontainers),它基于插入点的键对元素进行排序。

这将避免每次调用sort(…)时对性能的巨大影响(至少O(N*log(N)),其中N是元素的数量(逻辑上,这适用于这里建议使用sort(…)的所有此类解决方案)。考虑到对于所有这样的解决方案,sort(…)将需要在每次通过添加/删除元素修改后,当需要以排序方式访问集合时调用…

有一种简单的方法来整理字典。

根据你的问题,

解决方案是:

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)]

因此,通过将其更改为键、值和项,您可以像您想要的那样打印。希望这能有所帮助!

以下是建议解决方案的性能:

from collections import OrderedDict
from sortedcontainers import SortedDict
import json

keys = np.random.rand(100000)
vals = np.random.rand(100000)

d = dict(zip(keys, vals))

timeit SortedDict(d)
#45.8 ms ± 780 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

timeit sorted(d.items())
#91.9 ms ± 707 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

timeit OrderedDict(sorted(d.items(), key=lambda x: x[0]))
#93.7 ms ± 1.52 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

timeit dict(sorted(dic.items()))
#113 ms ± 824 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

timeit OrderedDict(sorted(dic.items()))
#122 ms ± 2.65 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

timeit json.dumps(d, sort_keys=True)
#259 ms ± 9.42 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

如我们所见,格兰特·詹克斯的解决方案是目前为止最快的。