程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Python practical basis] how to convert dict and JSON into each other

編輯:Python

Catalog

One 、 Actual combat scene

Two 、 Main knowledge points

3、 ... and 、 Rookie actual combat

1、 establish python file

2、 File directory

3、 Running results


One 、 Actual combat scene

Dictionaries dict and json How to transform each other , Transfer dictionary data to json Format write file , Then read it from the file and restore it to a dictionary .

Two 、 Main knowledge points

  • File read and write
  • Basic grammar
  • Multi level Dictionary
  • json 

3、 ... and 、 Rookie actual combat

Make arrangements now !

1、 establish python file

'''
Author: Rookie actual combat
Actual combat scene : Dictionaries dict and json How to transform each other
'''
# Import system package
import platform
import json
print("Hello, Rookie actual combat ")
print(" Actual combat scene : Dictionaries dict and json How to transform each other ")
# Input multilevel dictionary data
input_dict = {
"students": [
{"name": "John", "age": "15"},
{"name": "Anna", "age": "16"},
{"name": "Peter", "age": "16"}
],
"teachers": [
{"name": "Jack", "age": "30"},
{"name": "Jessy", "age": "33"}
]}
print(" input data : ", input_dict)
def dict_to_json():
# Dictionaries dict turn json, write file
with open("py013.json", "w") as f:
f.write(json.dumps(input_dict, indent=4))
def json_to_dict():
# json turn Dictionaries dict , Read from file
with open("py013.json") as f:
output_dict = json.loads(f.read())
print("json Results of dictionary conversion : ", output_dict)
dict_to_json()
json_to_dict()
print("Python edition ", platform.python_version())

2、 File directory

 py-013/
└── py013.py

3、 Running results

Hello, Rookie actual combat
Actual combat scene : Dictionaries dict and json How to transform each other  
input data :  {'students': [{'name': 'John', 'age': '15'}, {'name': 'Anna', 'age': '16'}, {'name': 'Peter', 'age': '16'}], 'teachers': [{'name': 'Jack', 'age': '30'}, {'name': 'Jessy', 'age': '33'}]}
json Results of dictionary conversion :  {'students': [{'name': 'John', 'age': '15'}, {'name': 'Anna', 'age': '16'}, {'name': 'Peter', 'age': '16'}], 'teachers': [{'name': 'Jack', 'age': '30'}, {'name': 'Jessy', 'age': '33'}]}
Python edition 3.10.4

Json Format data

{
"students": [
{
"name": "John",
"age": "15"
},
{
"name": "Anna",
"age": "16"
},
{
"name": "Peter",
"age": "16"
}
],
"teachers": [
{
"name": "Jack",
"age": "30"
},
{
"name": "Jessy",
"age": "33"
}
]
}

  Rookie actual combat , Continuous learning !


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved