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

时间:2022-01-07 00:35:35

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.

我尝试排序(self.docs_info.items),但它不起作用。

3 个解决方案

#1


16  

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 sorted on docs_info.items() (which is a sequence of tuples) is equivalent to sorting only by the keys.

由于字典键始终是唯一的,因此在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 int instead 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 access the 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 OrderedDict from the sorted (key, value) pairs:

这当然只是改变了访问字典元素的顺序,这通常就足够了(因为如果你没有访问它,那么如果它被排序了又有什么关系?)。如果由于某种原因你需要将dict本身“排序”,那么你将不得不使用collections.OrderedDict,它记住了项目插入的顺序。因此,您可以先对字典进行排序(如上所示),然后从排序(键,值)对中创建OrderedDict:

sorted_docs_info = collections.OrderedDict(sorted(docs_info.items()))

#2


8  

Standard Python dicts are "unordered". You can use an OrderedDict, take a look at the docs:

标准Python dicts是“无序的”。您可以使用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)])

#3


5  

If repeatedly sorting elements and inserting them in an ordered dict is too slow, consider one of the sorted dict implementations on PyPI. A SortedDict data type efficiently maintains its keys in sorted order. The sortedcontainers module contains one such implementation.

如果重复排序元素并将它们插入有序的dict中太慢,请考虑PyPI上的一个已排序的dict实现。 SortedDict数据类型有效地按排序顺序维护其键。 sortedcontainers模块包含一个这样的实现。

Installation from PyPI is easy:

从PyPI安装很简单:

pip install sortedcontainers

If you can't pip install then 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中实现,但是快速实现。

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 comparison of several popular implementations.

sortedcontainers模块还维护几个流行实现的性能比较。

#1


16  

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 sorted on docs_info.items() (which is a sequence of tuples) is equivalent to sorting only by the keys.

由于字典键始终是唯一的,因此在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 int instead 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 access the 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 OrderedDict from the sorted (key, value) pairs:

这当然只是改变了访问字典元素的顺序,这通常就足够了(因为如果你没有访问它,那么如果它被排序了又有什么关系?)。如果由于某种原因你需要将dict本身“排序”,那么你将不得不使用collections.OrderedDict,它记住了项目插入的顺序。因此,您可以先对字典进行排序(如上所示),然后从排序(键,值)对中创建OrderedDict:

sorted_docs_info = collections.OrderedDict(sorted(docs_info.items()))

#2


8  

Standard Python dicts are "unordered". You can use an OrderedDict, take a look at the docs:

标准Python dicts是“无序的”。您可以使用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)])

#3


5  

If repeatedly sorting elements and inserting them in an ordered dict is too slow, consider one of the sorted dict implementations on PyPI. A SortedDict data type efficiently maintains its keys in sorted order. The sortedcontainers module contains one such implementation.

如果重复排序元素并将它们插入有序的dict中太慢,请考虑PyPI上的一个已排序的dict实现。 SortedDict数据类型有效地按排序顺序维护其键。 sortedcontainers模块包含一个这样的实现。

Installation from PyPI is easy:

从PyPI安装很简单:

pip install sortedcontainers

If you can't pip install then 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中实现,但是快速实现。

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 comparison of several popular implementations.

sortedcontainers模块还维护几个流行实现的性能比较。