Python: Store a given dictionary in a json file
Write a Python program to store dictionary data in a JSON file.
Sample Solution:
Python Code:
# Create a dictionary 'd' containing information about students and teachers as a list of dictionaries.
d = {
"students": [
{"firstName": "Nikki", "lastName": "Roysden"},
{"firstName": "Mervin", "lastName": "Friedland"},
{"firstName": "Aron", "lastName": "Wilkins"}
],
"teachers": [
{"firstName": "Amberly", "lastName": "Calico"},
{"firstName": "Regine", "lastName": "Agtarap"}
]
}
# Print a message indicating the start of the code section and the original dictionary.
print("Original dictionary:")
print(d)
# Print the data type of the 'd' dictionary.
print(type(d))
# Import the 'json' module to work with JSON data.
import json
# Create a new JSON file named "dictionary" and write the 'd' dictionary to it with formatting.
with open("dictionary", "w") as f:
json.dump(d, f, indent=4, sort_keys=True)
# Print a message indicating the start of the next code section.
print("\nJson file to dictionary:")
# Open the "dictionary" JSON file and read its contents into the 'data' variable.
with open('dictionary') as f:
data = json.load(f)
# Print the 'data' dictionary containing the JSON data from the file.
print(data)
Sample Output:
Original dictionary: {'students': [{'firstName': 'Nikki', 'lastName': 'Roysden'}, {'firstName': 'Mervin', 'lastName': 'Friedland'}, {'firstName': 'Aron ', 'lastName': 'Wilkins'}], 'teachers': [{'firstName': 'Amberly', 'lastName': 'Calico'}, {'firstName': 'Regine', 'lastName': 'Agtarap'}]} <class 'dict'> Json file to dictionary: {'students': [{'firstName': 'Nikki', 'lastName': 'Roysden'}, {'firstName': 'Mervin', 'lastName': 'Friedland'}, {'firstName': 'Aron ', 'lastName': 'Wilkins'}], 'teachers': [{'firstName': 'Amberly', 'lastName': 'Calico'}, {'firstName': 'Regine', 'lastName': 'Agtarap'}]}
Flowchart:
Python Code Editor:
Previous: Write a Python program to match key values in two dictionaries.
Next: Write a Python program to create a dictionary of keys x, y, and z where each key has as value a list from 11-20, 21-30, and 31-40 respectively. Access the fifth value of each key from the dictionary.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics