Write list of dictionaries to file python

The way you will have to follow to write a dict to a file is kind different from the post you have mentioned.

First, you need serialize the object and than you persist it. These are fancy names for "write python objects to a file".

Python has 3 serialization modules included by default that you can use to achieve your objective. They are: pickle, shelve and json. Each one has its own characteristics and the one you have to use is the one which is more suitable to your project. You should check each module documentation to get more on it.

If your data will be only be accessed by python code, you can use shelve, here is an example:

import shelve

my_dict = {"foo":"bar"}

# file to be used
shelf = shelve.open("filename.shlf")

# serializing
shelf["my_dict"] = my_dict

shelf.close() # you must close the shelve file!!!

To retrieve the data you can do:

import shelve

shelf = shelve.open("filename.shlf") # the same filename that you used before, please
my_dict = shelf["my_dict"]
shelf.close()

See that you can treat the shelve object almost the same way you do with a dict.

In this article, we will discuss how to convert a list of dictionaries to JSON in python

Method 1: Using json.dumps()

This function will convert a list of dictionaries to JSON.

Syntax:

json.dumps(dict, indent)

Parameters:  

  • dictionary – name of a dictionary which should be converted to JSON object.
  • indent – defines the number of units for indentation

Example: Python program to create a list of dictionaries of employee data and convert to JSON

Python3

import json

data = [{"id": ("1", "2", "3"), "name": ("bhanu", "sivanagulu"), 

         "department": ("HR", "IT")},

        {"id": ("4", "5", "6"), "name": ("sai", "poori"),

         "department": ("HR", "IT")},

        {"id": ("7", "8", "9"), "name": ("teja", "gowtam"),

         "department": ("finance", "IT")},

        {"id": ("10", "11", "12"), "name": ("sai", "jyothi"),

         "department": ("business", "IT")},

        {"id": ("13", "14", "15"), "name": ("prudhvi", "nagendram"),

         "department": ("business", "IT")}]

final = json.dumps(data, indent=2)

print(final)

Output:

[
  {
    "id": [
      "1",
      "2",
      "3"
    ],
    "name": [
      "bhanu",
      "sivanagulu"
    ],
    "department": [
      "HR",
      "IT"
    ]
  },
  {
    "id": [
      "4",
      "5",
      "6"
    ],
    "name": [
      "sai",
      "poori"
    ],
    "department": [
      "HR",
      "IT"
    ]
  },
  {
    "id": [
      "7",
      "8",
      "9"
    ],
    "name": [
      "teja",
      "gowtam"
    ],
    "department": [
      "finance",
      "IT"
    ]
  },
  {
    "id": [
      "10",
      "11",
      "12"
    ],
    "name": [
      "sai",
      "jyothi"
    ],
    "department": [
      "business",
      "IT"
    ]
  },
  {
    "id": [
      "13",
      "14",
      "15"
    ],
    "name": [
      "prudhvi",
      "nagendram"
    ],
    "department": [
      "business",
      "IT"
    ]
  }
]

Method 2: Using json.dump()

This will write converted JSON data into a file.

Syntax:

json.dump(dict, file_pointer)

Parameters:  

  • dictionary – the name of dictionary which should be converted to JSON object.
  • file pointer – pointer of the file opened in write or append mode.

Syntax:

with open("mydata.json", "w") as final:
   json.dump(data, final)

where mydata is the new JSON file. Finally, we have to download the created JSON file

Syntax:

files.download('mydata.json')

Example:

Python3

from google.colab import files

import json

data = [{"id": ("1", "2", "3"), "name": ("bhanu", "sivanagulu"),

         "department": ("HR", "IT")},

        {"id": ("4", "5", "6"), "name": ("sai", "poori"),

         "department": ("HR", "IT")},

        {"id": ("7", "8", "9"), "name": ("teja", "gowtam"),

         "department": ("finance", "IT")},

        {"id": ("10", "11", "12"), "name": ("sai", "jyothi"),

         "department": ("business", "IT")},

        {"id": ("13", "14", "15"), "name": ("prudhvi", "nagendram"),

         "department": ("business", "IT")}]

with open("mydata.json", "w") as final:

    json.dump(data, final)

files.download('mydata.json')

Output:

[{“id”: [“1”, “2”, “3”], “name”: [“bhanu”, “sivanagulu”], “department”: [“HR”, “IT”]}, {“id”: [“4”, “5”, “6”], “name”: [“sai”, “poori”], “department”: [“HR”, “IT”]}, {“id”: [“7”, “8”, “9”], “name”: [“teja”, “gowtam”], “department”: [“finance”, “IT”]}, {“id”: [“10”, “11”, “12”], “name”: [“sai”, “jyothi”], “department”: [“business”, “IT”]}, {“id”: [“13”, “14”, “15”], “name”: [“prudhvi”, “nagendram”], “department”: [“business”, “IT”]}]


How do I put a list of dictionaries in a csv file?

List of Dictionaries to CSV in Python using csv..
Instead of creating a csv. writer object, we will create a csv. ... .
After creating the DictWriter object, we will add the header to the csv file. ... .
After adding the header, we can add the entire list of dictionaries to the csv file using the writerows() method..

How do you write a list to a file in python?

Steps to Write List to a File in Python.
Open file in write mode. Pass file path and access mode w to the open() function. ... .
Iterate list using a for loop. Use for loop to iterate each item from a list. ... .
Write current item into the file. ... .
Close file after completing the write operation..

How do I save a dict list?

We are going to explain all the above methods..
Method 1: Save dictionary in CSV format..
Method 2: Save the dict to a text file in JSON format (append mode).
Method 3: Save the dictionary objects to a file in txt form..
Method 4: Save the dict object to a file using the pickle method..
Conclusion..

Is JSON a list of dictionaries?

JSON, or JavaScript Object Notation, is a broader format used to encompass dictionary and list structures as shown in the image below. JSON: List and Dictionary Structure, Image by Author. The technical documentation says a JSON object is built on two structures: a list of key-value pairs and an ordered list of values.