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

1489

如何根据字典的键进行排序?

示例输入:

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

期望的输出:

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

6
我的使用场景是我有一个CLI应用程序,它有一个简单的菜单,菜单选项作为字典键存在。我想按字母顺序显示这些键,以使用户更加方便使用。 - Randy
2
“字典未排序” - 并非普遍真实。例如,Java拥有TreeMap(https://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html),它的行为完全符合OP的要求。 - Nayuki
14
请注意,字典现在按照插入顺序排序(Python 3.6+)。以下部分答案指出了这一点。 - matiasg
4
请注意,在Python 3.6中,保持插入顺序的字典是CPython的一个实现细节。直到Python 3.7,字典的插入顺序保持才正式成为语言的一部分。 - robertspierre
排序后的字典 = dict(sorted(my_dict.items())) - undefined
33个回答

23

一个简单的方法来实现这个:

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

s = {k : d[k] for k in sorted(d)}

s
Out[1]: {1: 89, 2: 3, 3: 0, 4: 5} 

仅适用于Python 3.7+,其中dict是一个有序字典(OrderedDict)。 - kwarnke
1
@kwarnke 有点迂腐,但在Python 3.7+中,dict和OrderedDict并不相同,尽管dict在3.7+中当然是有序的。 - Bede Constantinides

20

在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

18

我发现一个简单的方法可以对字典进行排序,就是创建一个新的字典,基于你想要排序的字典的键值对进行排序。 如果你想要对 dict = {} 进行排序,使用相关的方法检索所有项目,使用 sorted() 函数对其进行排序,然后创建新的字典。

这里是使用字典推导式的代码:

sorted_dict = {k:v for k,v in sorted(dict.items())}

简洁明了! - undefined

17

根据您的问题,您可以通过按键对当前字典进行排序来创建一个新字典。

这是您的字典

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

使用 lambda 函数对这个字典进行排序,创建一个新的名为 d1 的字典。

d1 = dict(sorted(d.items(), key = lambda x:x[0]))

根据 d 的键按顺序排序,d1 应为 {1: 89, 2: 3, 3: 0, 4: 5}。


3
你甚至不需要指定排序键。d1 = dict(sorted(d.items()))就能正常运作。 - M.Vanderlee
为什么这不是最佳答案? - John S

14

有一种简单的方法可以对字典进行排序。

根据你的问题,

解决方案是:

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)]
因此,通过将其转换为键、值和项,您可以像您想要的那样进行打印。希望这可以帮助您!

13

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

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

但是,使用pprint时它将返回已排序的字典

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

11

以下是建议方案的性能表现:

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)

从我们看到的情况来看,Grant Jenks的解决方案是目前最快的。


1
SortedDict非常快,正是我所需要的。 - Lenn Dolling

9
会生成你想要的内容:
 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}

但这不是正确的做法,因为它可能会在不同的字典中显示不同的行为,我最近学到了这一点。因此,Tim在我的查询响应中提出了完美的方法,我在这里分享。

from collections import OrderedDict
sorted_dict = OrderedDict(sorted(D1.items(), key=lambda t: t[0]))

“show a distinct behavior with different dictionaries” 是什么意思?sorted 无法处理的是什么“distinct behavior”? - ingyhere

7

我认为最简单的方法是按键对字典进行排序,并将排序后的键值对保存在新的字典中。

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

6

我提出了一种单行字典排序方法。

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

希望这对您有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接