一般常规的我们保存数据为dict类型时,系统会自动帮我们排序;但有时我们想按照输入顺序的key:value保存到dict中,而不想要改变顺序,则我们可以通过使用collecions,进行排序。
collections是一个python的内建模块。
示例如下:
# -*- coding:utf-8 -*-
#dic = {}
dic = dict()
dic['b'] = 1
dic['a'] = 2
dic['b0'] = 3
dic['a1'] = 4
print("dic is:",dic.items())
import json
jsons = json.dumps(dic)
print("jsons:",jsons)
结果:
('dic is:', [('a', 2), ('a1', 4), ('b', 1), ('b0', 3)])
('jsons:', '{"a": 2, "a1": 4, "b": 1, "b0": 3}')
修改后:
import collections
dic = collections.OrderedDict()
#dic = {}
dic['b'] = 1
dic['a'] = 2
dic['b0'] = 3
dic['a1'] = 4
print("dic is:",dic.items())
import json
jsons = json.dumps(dic)
print("jsons:",jsons)
结果:
('dic is:', [('b', 1), ('a', 2), ('b0', 3), ('a1', 4)])
('jsons:', '{"b": 1, "a": 2, "b0": 3, "a1": 4}')
补充拓展:Python字典转Json并使用多种格式实现
前言:
利用Python数据转换的套路可以遵循:变量定义的位置,字典操作,列表操作,这个三部分的内容可以处理大部分的数据相关需求。
1.下面我们先看这个脚本:
#从字典转换为Json的方法
from distutils.log import warn as printf
from json import dumps
from pprint import pprint
BOOKs = {
'0132269937': {
'title': 'Core Python Programming',
'edition': 2,
'year': 2007,
},
'0132356139': {
'title': 'Python Web Development with Django',
'authors': ['Jeff Forcier', 'Paul Bissex', 'Wesley Chun'],
'year': 2009,
},
'0137143419': {
'title': 'Python Fundamentals',
'year': 2009,
},
}
printf('*** RAW DICT ***')
printf(BOOKs)
printf('n*** PRETTY_PRINTED DICT ***')
pprint(BOOKs)
printf('n*** RAW JSON ***')
printf(dumps(BOOKs))
printf('n*** PRETTY_PRINTED JSON ***')
printf(dumps(BOOKs, indent=4))
输出结果:
"E:Anaconda3 4.2.0python.exe" E:/Pycharm/Python-code/dict2json.py
*** RAW DICT ***
{'0132269937': {'edition': 2, 'title': 'Core Python Programming', 'year': 2007},
'0132356139': {'authors': ['Jeff Forcier', 'Paul Bissex', 'Wesley Chun'],
{'0137143419': {'year': 2009, 'title': 'Python Fundamentals'}, '0132356139': {'year': 2009, 'authors': ['Jeff Forcier', 'Paul Bissex', 'Wesley Chun'], 'title': 'Python Web Development with Django'}, '0132269937': {'year': 2007, 'edition': 2, 'title': 'Core Python Programming'}}
'title': 'Python Web Development with Django',
'year': 2009},
*** PRETTY_PRINTED DICT ***
'0137143419': {'title': 'Python Fundamentals', 'year': 2009}}
*** RAW JSON ***
{"0137143419": {"year": 2009, "title": "Python Fundamentals"}, "0132356139": {"year": 2009, "authors": ["Jeff Forcier", "Paul Bissex", "Wesley Chun"], "title": "Python Web Development with Django"}, "0132269937": {"year": 2007, "edition": 2, "title": "Core Python Programming"}}
*** PRETTY_PRINTED JSON ***
{
"0137143419": {
"year": 2009,
"title": "Python Fundamentals"
},
"0132356139": {
"year": 2009,
"authors": [
"Jeff Forcier",
"Paul Bissex",
"Wesley Chun"
],
"title": "Python Web Development with Django"
},
"0132269937": {
"year": 2007,
"edition": 2,
"title": "Core Python Programming"
}
}
Process finished with exit code 0