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

后端 未结 7 1276
孤城傲影
孤城傲影 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:36

    Unpickle from file when program loads, modify as a normal dictionary in memory while program is running, pickle to file when program exits? Not sure exactly what more you're asking for here.

    0 讨论(0)
  • 2020-12-16 16:37

    If your keys (not necessarily the values) are strings, the shelve standard library module does what you want pretty seamlessly.

    0 讨论(0)
  • 2020-12-16 16:44

    pickling has one disadvantage. it can be expensive if your dictionary has to be read and written frequently from disk and it's large. pickle dumps the stuff down (whole). unpickle gets the stuff up (as a whole).

    if you have to handle small dicts, pickle is ok. If you are going to work with something more complex, go for berkelydb. It is basically made to store key:value pairs.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-16 16:47

    My favorite method (which does not use standard python dictionary functions): Read/write YAML files using PyYaml. See this answer for details, summarized here:

    Create a YAML file, "employment.yml":

    new jersey:
      mercer county:
        pumbers: 3
        programmers: 81
      middlesex county:
        salesmen: 62
        programmers: 81
    new york:
      queens county:
        plumbers: 9
        salesmen: 36
    

    Step 3: Read it in Python

    import yaml
    file_handle = open("employment.yml")
    my__dictionary = yaml.safe_load(file_handle)
    file_handle.close()
    

    and now my__dictionary has all the values. If you needed to do this on the fly, create a string containing YAML and parse it wth yaml.safe_load.

    0 讨论(0)
  • 2020-12-16 16:52

    If using only strings as keys (as allowed by the shelve module) is not enough, the FileDict might be a good way to solve this problem.

    0 讨论(0)
提交回复
热议问题