Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add a new dictionary into a JSON file?

In a simple words, I want to add a new dict to a pre-existing JSON file with dictionaries
From this

{
    "product1": {
      "id": "129",
      "price": 1200,
      "quantity": 12
    },
}

To this:

{
    "product1": {
      "id": "129",
      "price": 1200,
      "quantity": 12
    },

    "product2": {
      "id": "128",
      "price": 1300,
      "quantity": 41
    }
}

I want to create a function that adds a new dictionary into the pre-existing JSON file.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I thought of something as this:

data = json.load(open('productos.json'))

productname = input("Product name: ")
id = input("Id")
price = int(input("price: "))
quantity = int(input("quantity: "))

data[productname]["id"] = id

And so on… but I don’t know how to do it.

I used the method of converting the dict into list, but I want to access the data as data[productname] not as data[0][1].

>Solution :

You need to create a new dictionary containing the information that was entered, and then write the data dictionary back to the file.

data[productname] = {
    "id": id,
    "price": price,
    "quantity": quantity
}
with open("productos.json", "w") as f:
    json.dump(data, f)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading