How to take a word from a dictionary by its definition
Question: I am creating a code where I need to take a string of words, convert it into
numbers where `hi bye hi hello` would turn into `0 1 0 2`. I have used
dictionary's to do this and this is why I am having trouble on the next part.
I then need to compress this into a text file, to then decompress and
reconstruct it into a string again. This is the bit I am stumped on.

The way I would like to do it is by compressing the indexes of the numbers, so
the `0 1 0 2` bit into the text file with the dictionary contents, so in the
text file it would have `0 1 0 2` and `{hi:0, bye:1, hello:3}`.

Now what I would like to do to decompress or read this into the python file,
to use the _indexes_(this is how I will refer to the `0 1 0 2` from now on) to
then take each word out of the dictionary and reconstruct the sentence, so if
a **0** came up, it would look into the dictionary and then find what has a
`0` definition, then pull that out to put into the string, so it would find
`hi` and take that.

I hope that this is understandable and that at least one person knows how to
do it, because I am sure it is possible, however I have been unable to find
anything here or on the internet mentioning this subject.


Answer: Yes, you can just use regular dicts and lists to store the data. And use
`json` or `pickle` to persist the data to disk.

    
    
    import pickle
    
    s = 'hi hello hi bye'
    words = s.split()
    d = {}
    for word in word:
        if word not in d:
            d[word] = len(d)
    
    data = [d[word] for word in words]
    
    with open('/path/to/file', 'w') as f:
        pickle.dump({'lookup': d, 'data': data}, f)
    

Then read it back in

    
    
    with open('/path/to/file', 'r') as f:
        dic = pickle.load(f)
        d = d['lookup']
    reverse_d = {v: k for k, v in d.iteritems()}
    data = d['data']
    words = [reverse_d[index] for index in data]
    line = ' '.join(words)
    print line
    

