python的内建函数dict 是无序字典,如果想要字典有序使用 collections下的OrderedDict模块
# 无序字典
dict1 = dict()
dict1["name"] = "Nick"
dict1["age"] = 23
dict1["job"] = "it_worker"
for key,value in dict1.items():
print(key,":",value)
>>
age : 23
name : Nick
job : it_worker
# 有序字典
dict2 = OrderedDict()
dict2["a1"] = "a1"
dict2["b1"] = "b1"
dict2["c1"] = "c1"
for key,value in dict2.items():
print(key,":",value)
>>
a1 : a1
b1 : b1
c1 : c1
不过需要注意的是对于有序字典,如果两个字典内容相同,但是顺序不同,会被判定为2个不同的对象
dict3 = OrderedDict()
dict3["a1"] = "a1"
dict3["c1"] = "c1"
dict3["b1"] = "b1"
print(dict2 == dict3)
>> False