0

I made a program that reads the usr/share/dict/words file and creates key value pairs of words that have the same letters (eg. bkkooorw : ['bookwork', 'workbook'] )

I want to use this dictionary later to find words like
print dictpairs['bkkoorw'] # >>> bookwork workbook

This works fine but I don't want to make a dictionary every single time I run the program since this takes a lot of time and word in the dictionary won't change.

So, how do I read usr/share/dict/words and create a new file with the contents of the dictionary, dictpairs (without editing the words file). And keep that saved so then I can access that dictionary data from this current program. ?

from datetime import datetime
start_time = datetime.now()
import itertools 

f = open('/usr/share/dict/words', 'r') 
dictpairs = {} #create dictionary to later use remotely 

for word in f:
    sortedword = ''.join(sorted(word))[1:]
    if sortedword in dictpairs: 
        dictpairs[sortedword].append(word[:-1]) 
    else:
        dictpairs[sortedword] = [word[:-1]] 


end_time = datetime.now()
print('Duration: {}'.format(end_time - start_time)) #takes too long to run every time. I only need to run this once since the contents in usr/share/dict/word won't change. 

print dictpairs['bkkoorw'] #how do i use dictpairs remotely?

I really appreciate your help! please ask if my question's not very clear..

bisuke
  • 219
  • 3
  • 13
  • Quite a broad question. In general you'd want to try and open the cache file and if that fails, create it. There are [many](https://docs.python.org/2/library/json.html) [ways](https://docs.python.org/2/library/pickle.html) to serialize python objects for writing to a file. – Ilja Everilä Jun 01 '16 at 12:44
  • http://stackoverflow.com/questions/29720232/read-python-dict-from-file – Tom Myddeltyn Jun 01 '16 at 12:50

1 Answers1

0

it can be stored in local drive by pickle

import pickle

dictpairs  = {'bkkooorw' : ['bookwork', 'workbook']}
#store your dict
with open(fileName, 'wb') as handle:
  pickle.dump(dictpairs  , handle)
#load your dict
with open(fileName, 'rb') as handle:
 dictpairs = pickle.load(handle)
galaxyan
  • 5,944
  • 2
  • 19
  • 43