如何保留 python 字典中项目的顺序?

AKK*_*KKI 2 python dictionary

我有一本字典是这样说的:

a = {'first': 1, 'second': 2, 'third': 3}
Run Code Online (Sandbox Code Playgroud)

现在,当我打印时,它会以非常随机的顺序打印。而我需要它来始终保留订单。我怎样才能在Python中做到这一点?

use*_*re3 6

使用 OrderedDict 类。下面的例子。

from collections import OrderedDict

dict=OrderedDict()
dict['first']=1
dict['second']=2
dict['third']=3
dict
Run Code Online (Sandbox Code Playgroud)