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.
2
Answers
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 (alsoAge
should be 25 andGender
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:Output:
BTW
json_file
is a string and not a file.You can try these options to create a nested dictionary