python字典按照声明的顺序添加

原来的定义字典的代码如下:

dic = dict()
dic['a'] = 1
dic['b'] = 2
dic['c'] = 3
print(dic.items())

import json
jsons = json.dumps(dic)
print(jsons)

结果:

dic is: dict_items([('c', 3), ('b', 2), ('a', 1)])
jsons: {"c": 3, "b": 2, "a": 1}

这里通过使用collecions,进行排序。collections是一个python的内建模块。
修改后的代码:

import collections
dic = collections.OrderedDict()
# dic = dict()
dic['a'] = 1
dic['b'] = 2
dic['c'] = 3
print("dic is:",dic.items())

import json
jsons = json.dumps(dic)
print("jsons:",jsons)

结果:

dic is: odict_items([('a', 1), ('b', 2), ('c', 3)])
jsons: {"a": 1, "b": 2, "c": 3}

你可能感兴趣的:(python,json,python基础)