简体   繁体   中英

Writing a dictionary to a file in python

I want to write a complex List of dictionaries to a file. Below is my list of dictionaries:

[
  {
    "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":[]
    }
  }
]

I know how to write to a file in Python but I don't know how to parse this kind of complex list of dictionary.

Also I need to check for the List and If it is empty I should erase that dictionary (Eg: The second dictionary present in the above data) .

Please help me to solve this issue.Thanks a lot!

For something like that, I would use it to write it to a JSON file. You can do that like that

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

Try this:

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

Want to write complex objects to file? Then try to Pickle it.

(Above Answers are good but sharing another way)

Pickle is a way to serialize a python object and save to a file. Once you have done so, you de-serialize back when every you want it.

To Write

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)

To Read

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

Link: https://www.tutorialspoint.com/python-pickling

As for the part of the validation empty list, you can use len function if its empty and do as required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM