How to write a nested dictionary to json

不问归期 提交于 2020-05-10 07:25:32

问题


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


回答1:


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)


来源:https://stackoverflow.com/questions/21560433/how-to-write-a-nested-dictionary-to-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!