jinlong
jinlong

Reputation: 839

How to write a nested dictionary to json

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..!

Upvotes: 25

Views: 48802

Answers (1)

Joran Beasley
Joran Beasley

Reputation: 114088

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)

Upvotes: 41

Related Questions