简体   繁体   中英

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

I have a function which returns collections.OrderedDict() which is a payload for http post.

I need to log offline data when http post fails, so I want to write all dicts into a file and read it back as a list, I know I can create a list and keep appending to the list, but the need is to write into a file and read back into a list,

Could some one please help me to resolve this problem, please suggest if there is a better idea to retrieve dict items as a list

Use json for data serialization.

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 serializes the object to a string '[["a", 1], ["b", 2], ["c", 3]]' . Then json can read the data back in to a python object.

json is very common and is used in many languages. Most web apis use json to help make their app RESTful.

You could convert a list of dictionaries to a json and save it to a .json file. Then, reading it will be a piece of cake.

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])

Outputs:

{'hello': 'what up'}

This will work cleanly as long as the dictionary key/values are any of these types: dict, list, str, int, float, bool, None .

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