Catalog
One 、 Actual combat scene
Two 、 Main knowledge points
3、 ... and 、 Rookie actual combat
1、 establish python file
2、 File directory
3、 Running results
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 .
- File read and write
- Basic grammar
- Multi level Dictionary
- json
Make arrangements now !
''' 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())
py-013/
└── py013.py
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 !