使字典变成有序的

字典自己是无序的,当须要有序的使用字典时,能够借助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}
相关文章
相关标签/搜索