Home > Software design >  How can I create a json file using python which will contain one key and under that multiple key val
How can I create a json file using python which will contain one key and under that multiple key val

Time:12-07

I want my Json file to look like this- The Name values I am taking from another Json file.

{"Name1":{
    "Age": 30,
    "Gender": "Male",
},
"Name2":{
    "Age": 25,
    "Gender": "Female",
}}

My current script is like this:

Here I am fetching the name value from another Json file.

for k in data['person']:
    Name = k['name']
    dictionary =  {Name:{
        "Age": 25,
        "Gender": 'Female'
    }}
json_file = json.dumps(dictionary,indent = 4)

But I am getting output like -

{
    "Name1": {
        "Age": 35,
        "Gender": "Male"
    }
}{
    "Name2": {
        "Age": 30,
        "Gender": "Female"
    }
}

And so on like this.

Please help on this. Thanks in advance.

CodePudding user response:

I guess there is an indent mistake in your code and that you are actually dumping dictionary inside the loop. Hence the bad formatting of your output (also Age should be 25 and Gender Female for both elements since they are hardcoded in your loop).

You should first create an empty dictionary that you will update with dictionary at each step:

out_dict = {}
for k in data['person']:
    Name = k['name']
    dictionary =  {Name:{
        "Age": 25,
        "Gender": 'Female'
    }}
    out_dict.update(dictionary)

json_file = json.dumps(out_dict,indent = 4)

Output:

{
    "Name1": {
        "Age": 25,
        "Gender": "Female"
    },
    "Name2": {
        "Age": 25,
        "Gender": "Female"
    }
}

BTW json_file is a string and not a file.

CodePudding user response:

You can try these options to create a nested dictionary

import random 
import json
# Option 1
dummy_data = {'person': { f"Name{num}":{"Age": random.randint(9, 50) ,"Gender": random.choice(['Female', 'Male']) } for num in range(3)} } 
json_file = json.dumps(dummy_data, indent = 4)
json_file

# Option 2 
data_ditc = {
  "Name0": {
    "Age": 10,
    "Gender": "Male"
  },
  "Name1": {
    "Age": 29,
    "Gender": "Male"
  },
  "Name2": {
    "Age": 15,
    "Gender": "Male"
  }
}

data_person = {'person': {} } # = {'person': dict()}
for k, v in data_ditc.items():
  data_person['person'].update({k:v})

json_file2 = json.dumps(data_person, indent = 4)

# Option 3 

data_person2 = dict()
for item in data_ditc.items():
  data_person2.setdefault('person', {}).update(dict([item]))

json_file3 = json.dumps(data_person2, indent = 4)
  • Related