With Python, can I keep a persistent dictionary and modify it?

后端 未结 7 1325
孤城傲影
孤城傲影 2020-12-16 16:23

So, I want to store a dictionary in a persistent file. Is there a way to use regular dictionary methods to add, print, or delete entries from the dictionary in that file?

7条回答
  •  半阙折子戏
    2020-12-16 16:45

    Assuming the keys and values have working implementations of repr, one solution is that you save the string representation of the dictionary (repr(dict)) to file. YOu can load it using the eval function (eval(inputstring)). There are two main disadvantages of this technique:

    1) Is will not work with types that have an unuseable implementation of repr (or may even seem to work, but fail). You'll need to pay at least some attention to what is going on.

    2) Your file-load mechanism is basically straight-out executing Python code. Not great for security unless you fully control the input.

    It has 1 advantage: Absurdly easy to do.

提交回复
热议问题