Python实现字典 dict 和 json 相互转化
字典 dict 和 json 如何相互转化, 将字典数据转 json 格式写入文件,然后从文件中读取出来还原为字典。
- 文件读写
- 基础语法
- 多级字典
- json
使用的模块
import platform import json
# 我给大家准备了这些资料:Python视频教程、100本Python电子书、基础、爬虫、数据分析、web开发、机器学习、人工智能、面试题、Python学习路线图、问题解答! # 都放在这个扣群啦 : 279199867
输入多级字典数据
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_dict)
字典 dict 转 json, 写入文件
def dict_to_json(): with open("py013.json", "w") as f: f.write(json.dumps(input_dict, indent=4))
json 转 字典 dict , 从文件读取
def json_to_dict(): with open("py013.json") as f: output_dict = json.loads(f.read())
全部代码
import platform import json print("孟曰:如欲平治天下,当今之世,舍我其谁也?") print("字典 dict 和 json 如何相互转化 ") 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_dict) def dict_to_json(): with open("py013.json", "w") as f: f.write(json.dumps(input_dict, indent=4)) def json_to_dict(): with open("py013.json") as f: output_dict = json.loads(f.read()) print("json 转字典的结果: ", output_dict) dict_to_json() json_to_dict() print("Python 版本", platform.python_version())
效果展示
Json 格式数据
{ "students": [ { "name": "John", "age": "15" }, { "name": "Anna", "age": "16" }, { "name": "Peter", "age": "16" } ], "teachers": [ { "name": "Jack", "age": "30" }, { "name": "Jessy", "age": "33" } ] }
兄弟们,今天的分享就到这,再见!
来都来了,点个关注再走呗!