python通過對字典的排序,對json欄位進行排序
阿新 • • 發佈:2019-02-07
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}