如何按数字顺序按关键字对字典进行排序 Python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22264956/
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
How to sort dictionary by key in numerical order Python
提问by Justin
Here is the dictionary looks like:
这是字典的样子:
{'57481': 50, '57480': 89, '57483': 110, '57482': 18, '57485': 82, '57484': 40}
I would like to sort the dictionary in numerical order, the result should be:
我想按数字顺序对字典进行排序,结果应该是:
{'57480': 89, '57481': 50, '57482': 18, '57483': 110, '57484': 40, '57485': 82}
I tried sorted(self.docs_info.items)but it doesn't work.
我试过了,sorted(self.docs_info.items)但没有用。
回答by elyase
Standard Python dicts are "unordered". You can use an OrderedDict, take a look at the docs:
标准 Python 字典是“无序的”。你可以使用一个OrderedDict,看看文档:
from collections import OrderedDict
d = {'57481': 50, '57480': 89, '57483': 110, '57482': 18, '57485': 82, '57484': 40}
OrderedDict(sorted(d.items(), key=lambda t: t[0]))
# OrderedDict([('57480', 89), ('57481', 50), ('57482', 18), ('57483', 110), ('57484', 40), ('57485', 82)])
回答by Henry Keiter
If you only need to sort by key, you're 95% there already. Assuming your dictionary seems to be called docs_info:
如果您只需要按键排序,那么您已经完成了 95% 的工作。假设您的字典似乎被称为docs_info:
for key, value in sorted(docs_info.items()): # Note the () after items!
print(key, value)
Since dictionary keys are always unique, calling sortedon docs_info.items()(which is a sequence of tuples) is equivalent to sorting only by the keys.
由于字典键总是唯一的,调用sorted上docs_info.items()(这是元组序列)等效于仅由键排序。
Do bear in mind that strings containing numbers sort unintuitively! e.g. "11"is "smaller" than "2". If you need them sorted numerically, I recommend making the keys intinstead of str; e.g.
请记住,包含数字的字符串排序不直观!例如"11"比“小” "2"。如果您需要按数字对它们进行排序,我建议您使用键int而不是str; 例如
int_docs_info = {int(k) : v for k, v in docss_info.items()}
This of course just changes the order in which you accessthe dictionary elements, which is usually sufficient (since if you're not accessing it, what does it matter if it's sorted?). If for some reason you need the dict itself to be "sorted", then you'll have to use collections.OrderedDict, which remembers the order in which items were inserted into it. So you could first sort your dictionary (as above) and then create an OrderedDictfrom the sorted (key, value) pairs:
这当然只是改变您访问字典元素的顺序,这通常就足够了(因为如果您不访问它,它是否已排序有什么关系?)。如果由于某种原因您需要对 dict 本身进行“排序”,那么您必须使用collections.OrderedDict,它会记住项目插入其中的顺序。所以你可以先对你的字典进行排序(如上),然后OrderedDict从排序的(键,值)对中创建一个:
sorted_docs_info = collections.OrderedDict(sorted(docs_info.items()))
回答by GrantJ
If repeatedly sorting elements and inserting them in an ordered dict is too slow, consider one of the sorted dict implementations on PyPI. A SortedDictdata type efficiently maintains its keys in sorted order. The sortedcontainersmodule contains one such implementation.
如果重复排序元素并将它们插入有序的 dict 太慢,请考虑 PyPI 上的排序 dict 实现之一。一个SortedDict数据类型有效地维持有序的钥匙。该sortedcontainers模块包含一个这样的实现。
Installation from PyPI is easy:
从 PyPI 安装很容易:
pip install sortedcontainers
If you can't pip installthen simply copy down the sortedlist.py and sorteddict.py files from the open-source repository. SortedContainers is implemented in pure-Python but is fast-as-C implementations.
如果你不能,pip install那么只需从开源存储库中复制 sortedlist.py 和 sorteddict.py 文件。SortedContainers 是用纯 Python 实现的,但它是快速的 C 实现。
Once installed simply:
一旦安装简单:
In [1]: from sortedcontainers import SortedDict
In [6]: SortedDict({'57481': 50, '57480': 89, '57483': 110, '57482': 18, '57485': 82, '57484': 40})
Out[6]: SortedDict({'57480': 89, '57481': 50, '57482': 18, '57483': 110, '57484': 40, '57485': 82})
The sortedcontainers module also maintains a performance comparisonof several popular implementations.
sortedcontainers 模块还维护了几种流行实现的性能比较。
回答by K.Novichikhin
In Python 3 sorted()has an optional parameter key. And in 3.6+ dictmaintains insertion order.
在 Python 3 中sorted()有一个可选参数key。并且在 3.6+ 中dict保持插入顺序。
keyspecifies a function of one argument that is used to extract a comparison key from each element initerable(for example,key=str.lower). The default value isNone(compare the elements directly).
key指定一个带一个参数的函数,用于从iterable(例如,key=str.lower)中的每个元素中提取比较键。默认值为None(直接比较元素)。
Therefore, what OP wants can be accomplished this way.
因此,OP想要的可以通过这种方式完成。
>>> d = {'57481': 50, '57480': 89, '57483': 110, '57482': 18, '57485': 82, '57484': 40}
>>> for key, value in sorted(d.items(), key=lambda item: int(item[0])):
... print(key, value)
57480 89
57481 50
57482 18
57483 110
57484 40
57485 82
Or if OP wants to create a new sorted dictionary.
或者如果 OP 想要创建一个新的排序字典。
>>> d = {'57481': 50, '57480': 89, '57483': 110, '57482': 18, '57485': 82, '57484': 40}
>>> d_sorted = {key:value for key, value in sorted(d.items(), key=lambda item: int(item[0]))}
>>> d_sorted
{'57480': 89, '57481': 50, '57482': 18, '57483': 110, '57484': 40, '57485': 82}
d.items()returns a list of tuples, e.g. ('57480': 89)and so on. The lambda functions takes this tuple and applies intfunction to the first value. And then the result is used for comparison.
d.items()返回元组列表,例如('57480': 89)等等。lambda 函数接受这个元组并将int函数应用于第一个值。然后将结果用于比较。

