在python中利用dict轉(zhuǎn)json按輸入順序輸出內(nèi)容方式
一般常規(guī)的我們保存數(shù)據(jù)為dict類型時(shí),系統(tǒng)會(huì)自動(dòng)幫我們排序;但有時(shí)我們想按照輸入順序的key:value保存到dict中,而不想要改變順序,則我們可以通過使用collecions,進(jìn)行排序。
collections是一個(gè)python的內(nèi)建模塊。
示例如下:
# -*- coding:utf-8 -*-#dic = {}dic = dict()dic[’b’] = 1dic[’a’] = 2dic[’b0’] = 3dic[’a1’] = 4print('dic is:',dic.items()) import jsonjsons = json.dumps(dic)print('jsons:',jsons) 結(jié)果:(’dic is:’, [(’a’, 2), (’a1’, 4), (’b’, 1), (’b0’, 3)])(’jsons:’, ’{'a': 2, 'a1': 4, 'b': 1, 'b0': 3}’) 修改后:import collectionsdic = collections.OrderedDict()#dic = {}dic[’b’] = 1dic[’a’] = 2dic[’b0’] = 3dic[’a1’] = 4print('dic is:',dic.items()) import jsonjsons = json.dumps(dic)print('jsons:',jsons) 結(jié)果:(’dic is:’, [(’b’, 1), (’a’, 2), (’b0’, 3), (’a1’, 4)])(’jsons:’, ’{'b': 1, 'a': 2, 'b0': 3, 'a1': 4}’)
補(bǔ)充拓展:Python字典轉(zhuǎn)Json并使用多種格式實(shí)現(xiàn)
前言:
利用Python數(shù)據(jù)轉(zhuǎn)換的套路可以遵循:變量定義的位置,字典操作,列表操作,這個(gè)三部分的內(nèi)容可以處理大部分的數(shù)據(jù)相關(guān)需求。
1.下面我們先看這個(gè)腳本:
#從字典轉(zhuǎn)換為Json的方法from distutils.log import warn as printffrom json import dumpsfrom pprint import pprintBOOKs = { ’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))
輸出結(jié)果:
'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
首先導(dǎo)入所需要的三個(gè)函數(shù):1)導(dǎo)入distutils.log.warn()用來應(yīng)對(duì)python2中print語(yǔ)句和python3中print()語(yǔ)句引起的差異;2)json.dumps(),用來返回一個(gè)表示python對(duì)象的字符串;pprint.pprint(),用來美觀地輸出python的對(duì)象。
BOOKs數(shù)據(jù)結(jié)構(gòu)是一個(gè)python字典,這里沒有用列表這樣扁平的數(shù)據(jù)結(jié)構(gòu),是因?yàn)樽值淇梢詷?gòu)建結(jié)構(gòu)化層次的屬性(BOOKs表示通過ISBN標(biāo)識(shí)的書籍還具備額外的信息:書名、作者、出版年份)。值得注意的是,在等價(jià)的json表示方法中會(huì)移除所有額外的逗號(hào)。
Python的Json模塊序列化與反序列化的過程分別是 encoding和 decoding。encoding-把一個(gè)Python對(duì)象編碼轉(zhuǎn)換成Json字符串;decoding-把Json格式字符串解碼轉(zhuǎn)換成Python對(duì)象。要使用json模塊必須先import json
Json的導(dǎo)入導(dǎo)出
用write/dump是將Json對(duì)象輸入到一個(gè)python_object中,如果python_object是文件,則dump到文件中;如果是對(duì)象,則dump到內(nèi)存中。這是序列化
2.縱向數(shù)據(jù)轉(zhuǎn)換為橫向數(shù)據(jù)
1.情況:由于目前spark直接生成的json是每行一個(gè)對(duì)象,類似以下的json數(shù)據(jù)格式
[ { 'cardno': 100000026235, 'trdate': '2015-12-25', 'otime': '16:13:33', 'dtime': '16:21:10', 'osite': 16, 'dsite': 15, 'tfc': 1 }]
2.需求:轉(zhuǎn)換成Json column arrays 數(shù)組格式 [{},{}]如下
{’cardno’: [100006734923], ’trdate’: [’2015-12-25’], ’dtime’: [’17:56:45’], ’dsite’: [40], ’osite’: [41], ’otime’: [’17:50:11’], ’tfc’: [1]}
3.Python代碼實(shí)現(xiàn):
import sysimport jsonwith 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)
切換本地文件路徑轉(zhuǎn)換。
以上這篇在python中利用dict轉(zhuǎn)json按輸入順序輸出內(nèi)容方式就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. css進(jìn)階學(xué)習(xí) 選擇符2. html清除浮動(dòng)的6種方法示例3. ASP中解決“對(duì)象關(guān)閉時(shí),不允許操作。”的詭異問題……4. ASP基礎(chǔ)知識(shí)Command對(duì)象講解5. ASP.NET Core按用戶等級(jí)授權(quán)的方法6. HTML <!DOCTYPE> 標(biāo)簽7. XML入門精解之結(jié)構(gòu)與語(yǔ)法8. asp知識(shí)整理筆記4(問答模式)9. 淺談SpringMVC jsp前臺(tái)獲取參數(shù)的方式 EL表達(dá)式10. .NET6打包部署到Windows Service的全過程
