使字典變成有序的

字典自己是無序的,當須要有序的使用字典時,能夠藉助collections模塊中的OrderedDict類。
在迭代操做是它會保持元素被插入時的順序:

例如:json

import json
from collections import OrderedDict
dic_normal = {'a': 1, 'b': 2, 'c': 3}
dic_order = OrderedDict()
dic_order['a'] = 1
dic_order['b'] = 2
dic_order['c'] = 3
print json.dumps(dic_normal)
print json.dumps(dic_order)

輸出:code

{"a": 1, "c": 3, "b": 2}
{"a": 1, "b": 2, "c": 3}
相關文章
相關標籤/搜索