在 python 中将字典写入文件
Writing a dictionary to a file in python
我想将复杂的词典列表写入文件。以下是我的词典列表:
[
{
"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)
。
请多多帮我解决这个问题issue.Thanks!
对于类似的东西,我会用它来将它写入 JSON 文件。你可以那样做
import pandas as pd
df = pd.DataFrame(your_complex_dataset)
df.to_json('file_name.json')
试试这个:
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
想要将复杂对象写入文件?然后尝试腌制它。
(以上答案都很好,但换一种方式分享)
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)
Link: https://www.tutorialspoint.com/python-pickling
关于验证空列表的部分,如果为空可以使用len
函数,按要求进行。
我想将复杂的词典列表写入文件。以下是我的词典列表:
[
{
"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)
。
请多多帮我解决这个问题issue.Thanks!
对于类似的东西,我会用它来将它写入 JSON 文件。你可以那样做
import pandas as pd
df = pd.DataFrame(your_complex_dataset)
df.to_json('file_name.json')
试试这个:
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
想要将复杂对象写入文件?然后尝试腌制它。
(以上答案都很好,但换一种方式分享)
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)
Link: https://www.tutorialspoint.com/python-pickling
关于验证空列表的部分,如果为空可以使用len
函数,按要求进行。