简体   繁体   English

根据字典的键对字典进行排序(所有键均为整数时)

[英]Sort a Dictionary in Python Based on its Keys (when all keys are ints)

Basically, I have a dictionary where all the keys are ints where the highest keys are at the end of the list and the lower keys are at the start (sort of like a list). 基本上,我有一个字典,其中所有键都是整数,其中最高键在列表的末尾,而较低键在开始(有点像列表)。

Note I can't use a list for reasons I won't go into. 请注意,出于某些原因,我无法使用列表。

Python's ordered dictionary is what you are looking for. 您正在寻找Python的有序词典 For example 例如

>>> from collections import OrderedDict
>>> data = {4:'str1', 19:'str2', 1:'str3', 7:'str4'}
>>> orderedData = OrderedDict(sorted(data.items()))
>>> orderedData
OrderedDict([(1, 'str3'), (4, 'str1'), (7, 'str4'), (19, 'str2')])

You can still deal with an OrderedDict the same way you can deal with a normal dictionary, so 您仍然可以像处理普通字典一样处理OrderedDict ,因此

>>> orderedData[1]
'str3'
>>> orderedData[11] = 'str5'
>>> orderedData
OrderedDict([(1, 'str3'), (4, 'str1'), (7, 'str4'), (19, 'str2'), (11, 'str5')])

Also, this will work with any kind of key, ints not required. 此外,这将与任何类型的键(不需要ints使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM