Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to add dictionary object name to json object

I have 3 python dictionaries as below:

gender = {'Female': 241, 'Male': 240}
marital_status = {'Divorced': 245, 'Engaged': 243, 'Married': 244, 'Partnered': 246, 'Single': 242}
family_type = {'Extended': 234, 'Joint': 235, 'Nuclear': 233, 'Single Parent': 236}

I add them to a list:

lst = [gender, marital_status, family_type]

And create a JSON object which I need to save as a JSON file using pd.to_json using:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

jf = json.dumps(lst, indent = 4)

When we look at jf object:

print(jf)
[
    {
        "Female": 241,
        "Male": 240
    },
    {
        "Divorced": 245,
        "Engaged": 243,
        "Married": 244,
        "Partnered": 246,
        "Single": 242
    },
    {
        "Extended": 234,
        "Joint": 235,
        "Nuclear": 233,
        "Single Parent": 236
    }
]

Is there a way to make the dictionary name as key and get output as below:

{
"gender": {
    "Female": 241,
    "Male": 240
},
"marital_status": {
    "Divorced": 245,
    "Engaged": 243,
    "Married": 244,
    "Partnered": 246,
    "Single": 242
},
"family_type": {
    "Extended": 234,
    "Joint": 235,
    "Nuclear": 233,
    "Single Parent": 236
}
}

>Solution :

You’ll have to do this manually by creating a dictionary and mapping the name to the sub_dictionary yourself.

my_data = {'gender': gender, 'marital_status':marital_status, 'family_type': family_type}

Edit: example of adding to an outfile using json.dump

with open('myfile.json','w') as wrtier:
    json.dump(my_data, writer)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading