Lucifer
Lucifer

Reputation: 156

Updating Child Dictionary in python Then append new Data to it

Here's My code I want to create a JSON file from python and then want to take user input and add it to the dictionary and when it's looping it will again ask for entering user input AND THEN IT SHOULD append to child dictionary. I hope you Understand through Program below:

My Code:

 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()

My Output

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

Required Output

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

Please Tell me in the simple format how to do it. Tested dict.update() but nothing seems to work. Help!

Upvotes: 0

Views: 105

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 148965

Oops, a simple glance at the expected output shows that adding things at the end of the file cannot work: { "Main": { should only exist at the beginning of the file, and the closing part } } only at the end.

As you already use json to format your dictionary, you could simply update Intro["Main"] with new values, and rewrite the file instead of appending to it. Code could become with minimal changes:

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()

Upvotes: 1

Related Questions