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

时间:2015-07-30 04:46:38

标签: python dictionary

我有一个这样的字典说:

a = {'first': 1, 'second': 2, 'third': 3}

当我打印时,它以非常随机的顺序打印。而我需要它始终保持订单。我怎样才能在python中这样做?

1 个答案:

答案 0 :(得分:3)

使用OrderedDict类。示例如下。

from collections import OrderedDict

dict=OrderedDict()
dict['first']=1
dict['second']=2
dict['third']=3
dict