您的位置:首頁技術文章
文章詳情頁

在python中利用dict轉json按輸入順序輸出內容方式

瀏覽:5日期:2022-08-05 17:59:37

一般常規的我們保存數據為dict類型時,系統會自動幫我們排序;但有時我們想按照輸入順序的key:value保存到dict中,而不想要改變順序,則我們可以通過使用collecions,進行排序。

collections是一個python的內建模塊。

示例如下:

# -*- 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) 結果:(’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) 結果:(’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 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))

輸出結果:

'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

首先導入所需要的三個函數: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 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)

切換本地文件路徑轉換。

以上這篇在python中利用dict轉json按輸入順序輸出內容方式就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。

標簽: Python 編程
相關文章:
国产综合久久一区二区三区