在python中利用dict轉json按輸入順序輸出內容方式
一般常規的我們儲存資料為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:",jsons) 結果: ('dic is:',[('b',('a',3),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',} 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.0\python.exe" E:/Pycharm/Python-code/dict2json.py *** RAW DICT *** {'0132269937': {'edition': 2,'title': 'Core Python Programming','year': 2007},'0132356139': {'authors': ['Jeff Forcier',{'0137143419': {'year': 2009,'title': 'Python Fundamentals'},'0132356139': {'year': 2009,'title': 'Python Web Development with Django'},'0132269937': {'year': 2007,'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","Wesley Chun" ],"title": "Python Web Development with Django" },"0132269937": { "year": 2007,"title": "Core Python Programming" } } Process finished with exit code 0
首先匯入所需要的三個函式:1)匯入distutils.log.warn()用來應對python2中print語句和python3中print()語句引起的差異;2)json.dumps(),用來返回一個表示python物件的字串;pprint.pprint(),用來美觀地輸出python的物件。
BOOKs資料結構是一個python字典,這裡沒有用列表這樣扁平的資料結構,是因為字典可以構建結構化層次的屬性(BOOKs表示通過ISBN標識的書籍還具備額外的資訊:書名、作者、出版年份)。值得注意的是,在等價的json表示方法中會移除所有額外的逗號。
Python的Json模組序列化與反序列化的過程分別是 encoding和 decoding。encoding-把一個Python物件編碼轉換成Json字串;decoding-把Json格式字串解碼轉換成Python物件。要使用json模組必須先import json
Json的匯入匯出
用write/dump是將Json物件輸入到一個python_object中,如果python_object是檔案,則dump到檔案中;如果是物件,則dump到記憶體中。這是序列化
2.縱向資料轉換為橫向資料
1.情況:由於目前spark直接生成的json是每行一個物件,類似以下的json資料格式
[ { "cardno": 100000026235,"trdate": "2015-12-25","otime": "16:13:33","dtime": "16:21:10","osite": 16,"dsite": 15,"tfc": 1 }]
2.需求:轉換成Json column arrays 陣列格式 [{},{}]如下
{'cardno': [100006734923],'trdate': ['2015-12-25'],'dtime': ['17:56:45'],'dsite': [40],'osite': [41],'otime': ['17:50:11'],'tfc': [1]}
3.Python程式碼實現:
import sys import json with open(r'D:/data.json','r') as f: data = json.load(f) # test = { # "cardno": 100006734923,# "trdate": "2015-12-25",# "otime": "17:50:11",# "dtime": "17:56:45",# "osite": 41,# "dsite": 40,# "tfc": 1 # } result = {"cardno": [],"trdate":[],"otime":[],"dtime":[],"osite":[],"dsite":[],"tfc":[]} for test in data: for a in test.keys(): result[a].append(test[a]); print(result)
切換本地檔案路徑轉換。
以上這篇在python中利用dict轉json按輸入順序輸出內容方式就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。