如何将 OrderedDicts 写入文件并将其读回列表?

How to write OrderedDicts into a file and read it back to a list?

我有一个函数 returns collections.OrderedDict() 它是 http post.

的有效负载

我需要在 http post 失败时记录离线数据,所以我想将所有字典写入一个文件并将其作为列表读回,我知道我可以创建一个列表并继续附加到列表,但需要写入文件并读回列表,

有人可以帮我解决这个问题吗,如果有更好的主意来检索字典项目作为列表,请提出建议

您可以将字典列表转换为 json 并将其保存到 .json 文件。 那么,阅读起来就是小菜一碟了。

from collections import OrderedDict
import json
dic = OrderedDict()
dic['hello'] = 'what up'
dic_2 = OrderedDict()
dic_2['hey, second'] = 'Nothing is up'

with open('file.json', 'w') as f:
    dictionaries = [dic, dic_2]
    f.write(json.dumps(dictionaries))
with open('file.json', 'r') as read_file:
    loaded_dictionaries = json.loads(read_file.read())
    print(loaded_dictionaries[0])

输出:

{'hello': 'what up'}

只要字典 key/values 是以下任何一种类型,它就可以正常工作:dict, list, str, int, float, bool, None.

使用json进行数据序列化。

import json
import collections

d = collections.OrderedDict([('a', 1), ('b', 2), ('c', 3)])

s = json.dumps(list(d.items()))
print(s)

value = json.loads(s)
print(value)

json 将对象序列化为字符串 '[["a", 1], ["b", 2], ["c", 3]]'。然后 json 可以将数据读回 python 对象。

json 很常见,在许多语言中都有使用。大多数网络 API 使用 json 来帮助制作他们的应用程序 RESTful.