python基礎教程:在python中利用dict轉json按輸入順序輸出內容方式

今天小編就爲大家分享一篇在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:",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.0\python.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 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按輸入順序輸出內容方式就是小編分享給大家的全部內容了
推薦我們的python學習基地,點擊進入,看老程序是如何學習的!從基礎的python腳本、爬蟲、django

、數據挖掘等編程技術,工作經驗,還有前輩精心爲學習python的小夥伴整理零基礎到項目實戰的資料

,!每天都有程序員定時講解Python技術,分享一些學習的方法和需要留意的小細節

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章