用python将字典写入文件

keerthi007

我想将一个复杂的词典列表写入文件。以下是我的词典列表:

[
  {
    "Year": "2015",
    "Movies": {
      "type": "Horror",
      "Total Hours": "3",
      "Trimmed": 3000,
      "List": [
        {
          "date": "20/10/15",
          "time": "10:00:00",
          "type": "Horror",
          "text": "abcjsaadasd",
          "start": 00:00:00,
          "end": 02:59:13
          "Hero":"asfaf"
        },
        {
          "date": "22/10/15",
          "time": "11:00:00",
          "type": "Horror",
          "text": "sdvsdnsdfa",
          "start": 00:00:00,
          "end": 02:55:10,
          "Hero":"dsvsfs"
        }
      ]
    }
  },
  {
    "Year": "2016",
    "Movies": {
      "type": "Thriller",
      "Total Hours": "3",
      "Trimmed":100,
      "List":[]
    }
  }
]

我知道如何在Python中写入文件,但我不知道如何解析这种复杂的字典列表。

另外,我需要检查List和。如果为空,则应该删除该字典(Eg: The second dictionary present in the above data)

请帮助我解决此问题。非常感谢!

加比

尝试这个:

import json
# filter out all dicts with empty List
filtered_data = [d for d in data if d.get("Movies", {}).get("List")] 
# write the filtered data 
with open("output.json", "w") as f:
    json.dump(filtered_data, f) into a file

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章