0

I'm interested in Python 3 code that writes a hash to a disk file as a hash and then code that imports it into a script directly as a hash.

If importing wouldn't work then I'd be content to open and read a file, but I'd prefer not to have to rebuild a hash from a list every single time. I know that creating a list from a file is trivial, but searching a list is prohibitively slow in my script, so I want to use a hash because of the faster search. I don't actually need key-value pairs, just a list, and the hash would be purely to benchmark execution speeds at first. Thanks for all replies.

hft
  • 1,245
  • 10
  • 29
mickeyk
  • 1
  • 1
  • 1
    By "hash" do you mean dictionary object? – spirulence Jan 29 '15 at 03:51
  • Or "hash" --> "hash table"? – hft Jan 29 '15 at 04:02
  • If you have a dictionary (or any object) I believe you can use the "pickle" module to do what you want... if I understand your question... – hft Jan 29 '15 at 04:03
  • Show us your data: what does it look like? You might want to look into the `json` or `pickle` modules. – Hai Vu Jan 29 '15 at 04:04
  • FWIW, a Python dictionary object is implemented as a hash table, as mentioned [here](http://stackoverflow.com/questions/114830/is-a-python-dictionary-an-example-of-a-hash-table). Unfortunately, the link in that question to Tim Peter's message on this topic is broken, but there's always the link to the [source code](http://svn.python.org/view/python/trunk/Objects/dictobject.c?view=markup)... – PM 2Ring Jan 29 '15 at 04:23
  • If you "don't actually need key-value pairs, just a list", then a Python `set` may be more suitable than a full `dict`. FWIW, I've used zlib compressed pickled `dict`s to maintain data between program runs. It's very fast as long as the amount of data isn't _too_ huge. – PM 2Ring Jan 29 '15 at 04:34

1 Answers1

0

In order to dump an object (such as a dictionary) into a file in a nice pythonic way, you can use the "pickle" module. For example:

import pickle
mydic={"k1":[1,2,3],"k2":[6,6,6],"k3":"cats"}
f=open("./somefile.bin","wb")
pickle.dump(mydic,f)

You can then load the dumped object using pickel.load(), as described in the python docs (other options are specified as well): https://docs.python.org/2/library/pickle.html

hft
  • 1,245
  • 10
  • 29