Convert a python dict to a string and back

后端 未结 10 1631
清酒与你
清酒与你 2020-11-27 10:17

I am writing a program that stores data in a dictionary object, but this data needs to be saved at some point during the program execution and loaded back into the dictionar

10条回答
  •  粉色の甜心
    2020-11-27 10:59

    I think you should consider using the shelve module which provides persistent file-backed dictionary-like objects. It's easy to use in place of a "real" dictionary because it almost transparently provides your program with something that can be used just like a dictionary, without the need to explicitly convert it to a string and then write to a file (or vice-versa).

    The main difference is needing to initially open() it before first use and then close() it when you're done (and possibly sync()ing it, depending on the writeback option being used). Any "shelf" file objects create can contain regular dictionaries as values, allowing them to be logically nested.

    Here's a trivial example:

    import shelve
    
    shelf = shelve.open('mydata')  # open for reading and writing, creating if nec
    shelf.update({'one':1, 'two':2, 'three': {'three.1': 3.1, 'three.2': 3.2 }})
    shelf.close()
    
    shelf = shelve.open('mydata')
    print shelf
    shelf.close()
    

    Output:

    {'three': {'three.1': 3.1, 'three.2': 3.2}, 'two': 2, 'one': 1}
    

提交回复
热议问题