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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15614067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:33:22  来源:igfitidea点击:

How to sort a dictionary by key?

pythonsortingdictionary

提问by Imoum

i tried to sort dict by key but no chance. this is my dict :

我试图按键对 dict 进行排序,但没有机会。这是我的字典:

result={'1':'value1','2':'value2',...}

i'm using Python2.7 and i found this

我正在使用 Python2.7,我发现了这个

keys = result.keys()
keys.sort()

but this is not what i expected, i have an unsorted dict.

但这不是我所期望的,我有一个未排序的字典。

采纳答案by NPE

Standard Python dictionaries are inherently unordered. However, you could use collections.OrderedDict. It preserves the insertion order, so all you have to do is add the key/value pairs in the desired order:

标准 Python 词典本质上是无序的。但是,您可以使用collections.OrderedDict. 它保留了插入顺序,因此您所要做的就是按所需顺序添加键/值对:

In [4]: collections.OrderedDict(sorted(result.items()))
Out[4]: OrderedDict([('1', 'value1'), ('2', 'value2')])

回答by DonCallisto

Python dictionaries are unordered (for definition)

Python 字典是无序的(用于定义)

You can use OrderedDictinstead

您可以使用OrderedDict代替

回答by Jakub M.

sorted(result.iteritems(), key=lambda key_value: key_value[0])

This will output sorted results, but the dictionary will remain unsorted. If you want to maintain ordering of a dictionary, use OrderedDict

这将输出排序结果,但字典将保持未排序。如果要维护字典的顺序,请使用OrderedDict

Actually, if you sort by keyyou could skip the key=...part, because then the iterated items are sorted first by key and later by value (what NPE uses in his answer)

实际上,如果您按键排序,则可以跳过该key=...部分,因为然后迭代项首先按键排序,然后按值排序(NPE 在他的回答中使用的是什么)