如何按键对字典进行排序?
示例输入:
{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}
当前回答
就问题的表述方式而言,这里的大多数答案都是正确的。
然而,考虑到事情应该如何真正完成,考虑到几十年的计算机科学,让我完全惊讶的是,这里实际上只有一个答案(来自GrantJ用户)建议使用排序关联容器(sortedcontainers),它基于插入点的键对元素进行排序。
这将避免每次调用sort(…)时对性能的巨大影响(至少O(N*log(N)),其中N是元素的数量(逻辑上,这适用于这里建议使用sort(…)的所有此类解决方案)。考虑到对于所有这样的解决方案,sort(…)将需要在每次通过添加/删除元素修改后,当需要以排序方式访问集合时调用…
其他回答
2.7中两个方法的时间比较显示它们实际上是相同的:
>>> setup_string = "a = sorted(dict({2:3, 1:89, 4:5, 3:0}).items())"
>>> timeit.timeit(stmt="[(k, val) for k, val in a]", setup=setup_string, number=10000)
0.003599141953657181
>>> setup_string = "from collections import OrderedDict\n"
>>> setup_string += "a = OrderedDict({1:89, 2:3, 3:0, 4:5})\n"
>>> setup_string += "b = a.items()"
>>> timeit.timeit(stmt="[(k, val) for k, val in b]", setup=setup_string, number=10000)
0.003581275490432745
简单:
d = {2:3, 1:89, 4:5, 3:0}
sd = sorted(d.items())
for k,v in sd:
print k, v
输出:
1 89
2 3
3 0
4 5
对于CPython/PyPy 3.6,以及任何Python 3.7或更高版本,这很容易做到:
>>> d = {2:3, 1:89, 4:5, 3:0}
>>> dict(sorted(d.items()))
{1: 89, 2: 3, 3: 0, 4: 5}
我认为最简单的事情是按键对字典进行排序,并将排序的键:值对保存在一个新的字典中。
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
我想出了单行字典排序。
>> a = {2:3, 1:89, 4:5, 3:0}
>> c = {i:a[i] for i in sorted(a.keys())}
>> print(c)
{1: 89, 2: 3, 3: 0, 4: 5}
[Finished in 0.4s]
希望这对你有所帮助。