如何将嵌套字典写入json

时间:2014-02-04 18:27:38

标签: python json dictionary nested

我在Python中创建了一个嵌套字典,如下所示:

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

但我无法弄清楚如何将这个嵌套的dict写入json文件。任何意见将不胜感激..!

1 个答案:

答案 0 :(得分:26)

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)