开发者

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

开发者 https://www.devze.com 2023-04-13 01:53 出处:网络
Basically, I have a dictionary where all the keys are ints where the highest keys are at the en开发者_Go百科d of the list and the lower keys are at the start (sort of like a list).

Basically, I have a dictionary where all the keys are ints where the highest keys are at the en开发者_Go百科d 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. 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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号