溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

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

發布時間:2020-10-07 16:54:28 來源:腳本之家 閱讀:149 作者:zhw864680355 欄目:開發技術

一般常規的我們保存數據為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按輸入順序輸出內容方式就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持億速云。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女