用python将字典写入文件

时间:2020-07-12 11:56:29

标签: python json list dictionary io

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

[
  {
    "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)

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

3 个答案:

答案 0 :(得分:1)

对于类似的事情,我将使用它将其写入JSON文件。你可以那样做

import pandas as pd
df = pd.DataFrame(your_complex_dataset)
df.to_json('file_name.json')

答案 1 :(得分:1)

尝试一下:

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

答案 2 :(得分:1)

是否想将复杂的对象写入文件?然后尝试将它腌制。

(以上回答很好,但分享了另一种方式)

Pickle是一种将python对象序列化并保存到文件的方法。完成此操作后,您便会在需要时反序列化。

写作

import pickle
mylist = ['a', 'b', 'c', 'd'] # Instead of list, this can be you dict or so,..
with open('datafile.pickle', 'wb') as fh:
   pickle.dump(mylist, fh)

阅读

import pickle
pickle_off = open ("datafile.txt", "rb")
emp = pickle.load(pickle_off)
print(emp)

链接:https://www.tutorialspoint.com/python-pickling

对于验证空白列表的一部分,您可以使用len函数(如果为空),并根据需要进行操作。