Home > OS >  how to add dictionary object name to json object
how to add dictionary object name to json object

Time:11-17

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:

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
}
}

CodePudding user response:

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)

CodePudding user response:

As per your requirement you can done it like this by replacing line lst

dict_req = {"gender":gender, "marital_status":marital_status, "family_type":family_type}
  • Related