Home > OS >  How to add a new dictionary into a JSON file?
How to add a new dictionary into a JSON file?

Time:02-17

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.

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].

CodePudding user response:

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)
  • Related