Python Disk-Based Dictionary

后端 未结 8 1643
逝去的感伤
逝去的感伤 2020-12-04 16:44

I was running some dynamic programming code (trying to brute-force disprove the Collatz conjecture =P) and I was using a dict to store the lengths of the chains I had alread

相关标签:
8条回答
  • 2020-12-04 17:23

    The shelve module may do it; at any rate, it should be simple to test. Instead of:

    self.lengths = {}
    

    do:

    import shelve
    self.lengths = shelve.open('lengths.shelf')
    

    The only catch is that keys to shelves must be strings, so you'll have to replace

    self.lengths[indx]
    

    with

    self.lengths[str(indx)]
    

    (I'm assuming your keys are just integers, as per your comment to Charles Duffy's post)

    There's no built-in caching in memory, but your operating system may do that for you anyway.

    [actually, that's not quite true: you can pass the argument 'writeback=True' on creation. The intent of this is to make sure storing lists and other mutable things in the shelf works correctly. But a side-effect is that the whole dictionary is cached in memory. Since this caused problems for you, it's probably not a good idea :-) ]

    0 讨论(0)
  • 2020-12-04 17:23

    With a little bit of thought it seems like you could get the shelve module to do what you want.

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