使用 collections.OrderedDict 来保持有序字典
虽然 Python 3.7+ 中普通字典默认已保持插入顺序,但如果需要兼容旧版本或者明确表达有序意图,可以使用 collections 模块的 OrderedDict。
示例如下:
from collections import OrderedDict
my_dict = {'b': 2, 'a': 1, 'c': 3}
sorted_items = sorted(my_dict.items())
ordered_dict = OrderedDict(sorted_items)
print(ordered_dict) # 输出:OrderedDict([('a', 1), ('b', 2), ('c', 3)])
这样可以确保字典的顺序保持排序后的顺序。