gpt4 book ai didi

python - 在python中将字典写入文件

转载 作者:行者123 更新时间:2023-12-02 19:22:34 25 4
gpt4 key购买 nike

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

[
{
"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 写入文件,但我不知道如何解析这种复杂的字典列表。

我还需要检查列表,如果它是空的,我应该删除该字典(例如:上述数据中存在的第二个字典)

请帮我解决这个问题。非常感谢!

最佳答案

试试这个:

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

关于python - 在python中将字典写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62860785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com