Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a nested dictionary to json

Tags:

I created a nested dictionary in Python like this:

{
 "Laptop": {
            "sony": 1
            "apple": 2
            "asus": 5
          },
 "Camera": {
            "sony": 2
            "sumsung": 1
            "nikon" : 4
           },
}

But I couldn't figure out how to write this nested dict into a json file. Any comments will be appreciated..!

like image 757
jinlong Avatar asked Feb 04 '14 18:02

jinlong


People also ask

Can dictionary be converted to JSON?

To Convert dictionary to JSON you can use the json. dumps() which converts a dictionary to str object, not a json(dict) object! so you have to load your str into a dict to use it by using json.

How do I store a dictionary in JSON?

You can save the Python dictionary into JSON files using a built-in module json. We need to use json. dump() method to do this. Use the indent parameter to prettyPrint your JSON data.

How do I add a nested dictionary?

Addition of elements to a nested Dictionary can be done in multiple ways. One way to add a dictionary in the Nested dictionary is to add values one be one, Nested_dict[dict][key] = 'value'. Another way is to add the whole dictionary in one go, Nested_dict[dict] = { 'key': 'value'}.


1 Answers

d = {
 "Laptop": {
            "sony": 1,
            "apple": 2,
            "asus": 5,
          },
 "Camera": {
            "sony": 2,
            "sumsung": 1,
            "nikon" : 4,
           },
}
with open("my.json","w") as f:
    json.dump(d,f)
like image 51
Joran Beasley Avatar answered Oct 09 '22 03:10

Joran Beasley