在python中更新子字典,然后向其添加新数据

时间:2018-11-20 09:47:58

标签: json python-3.x

这是我的代码,我想从python创建一个JSON文件,然后想要接受用户输入并将其添加到字典中,并且在循环时,它将再次要求输入用户输入,然后应将其附加到子字典中。希望您能通过下面的程序理解

我的代码:

String.format("%02d:%02d:%02d", hh, mm, ss);

我的输出

 import json

 i = 0
 while True:
     value1 = input("Enter Your Name:")
     value2 = int(input("Enter Your Age:"))
     value3 = input("Enter Your City:")
     Data = int(input("Enter ID :"))
     # a Python object (dict):
     # yourself = {"Intro":{}}
     Intro = {}
     i += 1
     Intro["Main"] = {
            i: {
                "ID": Data,
                "name": value1,
                "age": value2,
                "city": value3
            }
        }
     #print(json.dumps(Intro, indent=3, sort_keys=False))
     y = json.dumps(Intro, indent=3, sort_keys=False)
     hat = open("data.json", "a+")
     hat.write(y)
     # # Json.write(",")
     # print(Json.readable())
     hat.seek(0)
     print(hat.read())
     hat.close()

必需的输出

{
 "Main": {
      "1": {
         "ID": 13,
         "name": "xxxx",
         "age": 22,
         "city": "xxxxx"
      }
   }
}{
   "Main": {
      "2": {
         "ID": 14,
         "name": "xxxx1",
         "age": 22,
         "city": "xxxxx"
      }
   }
}

请以简单格式告诉我如何操作。测试了dict.update(),但似乎没有任何效果。救命!

1 个答案:

答案 0 :(得分:0)

糟糕,对预期输出的简单浏览显示,无法在文件末尾添加内容:{ "Main": {仅应存在于文件的开头,而结尾部分仅为} }最后。

由于您已经使用json格式化字典,因此只需用新值更新Intro["Main"],然后重写文件即可,而不是附加到文件中。代码只需很少的更改即可:

import json

i = 0
Intro = {'Main': {}}       # Initialize Intro before first read
while True:
     value1 = input("Enter Your Name:")
     value2 = int(input("Enter Your Age:"))
     value3 = input("Enter Your City:")
     Data = int(input("Enter ID :"))

     # a Python object (dict):
     # yourself = {"Intro":{}}
     i += 1
     Intro["Main"].update({
            i: {
                "ID": Data,
                "name": value1,
                "age": value2,
                "city": value3
            }
        })
     #print(json.dumps(Intro, indent=3, sort_keys=False))
     y = json.dumps(Intro, indent=3, sort_keys=False)
     hat = open("data.json", "w+")         # use rewrite mode instead of append
     hat.write(y)
     # # Json.write(",")
     # print(Json.readable())
     hat.seek(0)
     print(hat.read())
     hat.close()