簡而言之,我想將新的字典添加到帶有字典的預先存在的 JSON 檔案中
{
"product1": {
"id": "129",
"price": 1200,
"quantity": 12
},
}
對此:
{
"product1": {
"id": "129",
"price": 1200,
"quantity": 12
},
"product2": {
"id": "128",
"price": 1300,
"quantity": 41
}
}
我想創建一個函式,將新字典添加到預先存在的 JSON 檔案中。
我想到了這樣的事情:
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
等等……但我不知道該怎么做。
我使用了將dict轉換為串列的方法,但我想訪問資料而data[productname]不是data[0][1].
uj5u.com熱心網友回復:
您需要創建一個包含輸入資訊的新字典,然后將data字典寫回檔案。
data[productname] = {
"id": id,
"price": price,
"quantity": quantity
}
with open("productos.json", "w") as f:
json.dump(data, f)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/429017.html
