How to Create a List of Dictionaries and Save Them in Python?

Estimated read time 2 min read

To create a list of dictionaries and save them in Python, you can use the json module to convert the list into a JSON string, and then write the JSON string to a file. Here’s an example code that creates a list of dictionaries and saves it to a file named data.json:

import json

# create a list of dictionaries
people = [
    {"name": "John", "age": 30, "city": "New York"},
    {"name": "Alice", "age": 25, "city": "San Francisco"},
    {"name": "Bob", "age": 40, "city": "Chicago"}
]

# convert the list into a JSON string
json_str = json.dumps(people)

# write the JSON string to a file
with open('data.json', 'w') as f:
    f.write(json_str)

In this example, we first import the json module. Then we create a list of dictionaries people, where each dictionary contains information about a person’s name, age, and city.

Next, we use the json.dumps() function to convert the people list into a JSON string. The resulting JSON string is stored in the json_str variable.

Finally, we use the open() function to open a file named data.json in write mode ('w'), and use the write() method to write the JSON string to the file. The with statement ensures that the file is automatically closed when the block is exited.

Note that you can also load the list of dictionaries back from the JSON file using the json.load() function. Here’s an example code that reads the data.json file and converts its contents back into a list of dictionaries:

with open('data.json', 'r') as f:
    json_str = f.read()

people = json.loads(json_str)
print(people)

In this example, we use the open() function to open the data.json file in read mode ('r'), and use the read() method to read its contents into the json_str variable.

Then we use the json.loads() function to convert the JSON string back into a Python list of dictionaries. The resulting list of dictionaries is stored in the people variable, and printed using the print() function.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply