Updating Child Dictionary in python Then append new Data to it











up vote
0
down vote

favorite












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!










share|improve this question


























    up vote
    0
    down vote

    favorite












    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!










    share|improve this question
























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      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!










      share|improve this question













      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!







      json python-3.x






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 20 at 9:47









      Raj Pandey

      34




      34
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote



          accepted










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





          share|improve this answer





















          • Serge Ballesta i am getting "ValueError:invalid mode:w+" error
            – Raj Pandey
            Nov 20 at 10:56










          • Thanks serge ballesta. Worked like a charm.
            – Raj Pandey
            Nov 20 at 11:01










          • Please can you give me reference to learn about multilayer dict with Json just like my example. It will of great Help.
            – Raj Pandey
            Nov 20 at 11:05










          • @RajPandey: I have no special reference. Json is just a textual representation of arrays and dictionnaries of primitive elements. Try to first think of the underlying structure and only in the end of the json representation.
            – Serge Ballesta
            Nov 20 at 11:16











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53390231%2fupdating-child-dictionary-in-python-then-append-new-data-to-it%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          0
          down vote



          accepted










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





          share|improve this answer





















          • Serge Ballesta i am getting "ValueError:invalid mode:w+" error
            – Raj Pandey
            Nov 20 at 10:56










          • Thanks serge ballesta. Worked like a charm.
            – Raj Pandey
            Nov 20 at 11:01










          • Please can you give me reference to learn about multilayer dict with Json just like my example. It will of great Help.
            – Raj Pandey
            Nov 20 at 11:05










          • @RajPandey: I have no special reference. Json is just a textual representation of arrays and dictionnaries of primitive elements. Try to first think of the underlying structure and only in the end of the json representation.
            – Serge Ballesta
            Nov 20 at 11:16















          up vote
          0
          down vote



          accepted










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





          share|improve this answer





















          • Serge Ballesta i am getting "ValueError:invalid mode:w+" error
            – Raj Pandey
            Nov 20 at 10:56










          • Thanks serge ballesta. Worked like a charm.
            – Raj Pandey
            Nov 20 at 11:01










          • Please can you give me reference to learn about multilayer dict with Json just like my example. It will of great Help.
            – Raj Pandey
            Nov 20 at 11:05










          • @RajPandey: I have no special reference. Json is just a textual representation of arrays and dictionnaries of primitive elements. Try to first think of the underlying structure and only in the end of the json representation.
            – Serge Ballesta
            Nov 20 at 11:16













          up vote
          0
          down vote



          accepted







          up vote
          0
          down vote



          accepted






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





          share|improve this answer












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






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 20 at 10:36









          Serge Ballesta

          75k956129




          75k956129












          • Serge Ballesta i am getting "ValueError:invalid mode:w+" error
            – Raj Pandey
            Nov 20 at 10:56










          • Thanks serge ballesta. Worked like a charm.
            – Raj Pandey
            Nov 20 at 11:01










          • Please can you give me reference to learn about multilayer dict with Json just like my example. It will of great Help.
            – Raj Pandey
            Nov 20 at 11:05










          • @RajPandey: I have no special reference. Json is just a textual representation of arrays and dictionnaries of primitive elements. Try to first think of the underlying structure and only in the end of the json representation.
            – Serge Ballesta
            Nov 20 at 11:16


















          • Serge Ballesta i am getting "ValueError:invalid mode:w+" error
            – Raj Pandey
            Nov 20 at 10:56










          • Thanks serge ballesta. Worked like a charm.
            – Raj Pandey
            Nov 20 at 11:01










          • Please can you give me reference to learn about multilayer dict with Json just like my example. It will of great Help.
            – Raj Pandey
            Nov 20 at 11:05










          • @RajPandey: I have no special reference. Json is just a textual representation of arrays and dictionnaries of primitive elements. Try to first think of the underlying structure and only in the end of the json representation.
            – Serge Ballesta
            Nov 20 at 11:16
















          Serge Ballesta i am getting "ValueError:invalid mode:w+" error
          – Raj Pandey
          Nov 20 at 10:56




          Serge Ballesta i am getting "ValueError:invalid mode:w+" error
          – Raj Pandey
          Nov 20 at 10:56












          Thanks serge ballesta. Worked like a charm.
          – Raj Pandey
          Nov 20 at 11:01




          Thanks serge ballesta. Worked like a charm.
          – Raj Pandey
          Nov 20 at 11:01












          Please can you give me reference to learn about multilayer dict with Json just like my example. It will of great Help.
          – Raj Pandey
          Nov 20 at 11:05




          Please can you give me reference to learn about multilayer dict with Json just like my example. It will of great Help.
          – Raj Pandey
          Nov 20 at 11:05












          @RajPandey: I have no special reference. Json is just a textual representation of arrays and dictionnaries of primitive elements. Try to first think of the underlying structure and only in the end of the json representation.
          – Serge Ballesta
          Nov 20 at 11:16




          @RajPandey: I have no special reference. Json is just a textual representation of arrays and dictionnaries of primitive elements. Try to first think of the underlying structure and only in the end of the json representation.
          – Serge Ballesta
          Nov 20 at 11:16


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53390231%2fupdating-child-dictionary-in-python-then-append-new-data-to-it%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          To store a contact into the json file from server.js file using a class in NodeJS

          Redirect URL with Chrome Remote Debugging Android Devices

          Dieringhausen