Custom Def #6: Python Pickles

Published June 3, 2020, 1:45 a.m.

Last time we had our code use words from a list that we provided in the code.  We would like a way to store variables long-term and even add to them so that our lists of words get incrementally longer over time. In python we can accomplish this with pickles.  Pickles are just python jargon for data stored in a binary file that can be called upon at a later date.   This will require a module that we have not used yet, so we must first go to the top of our file and import the pickle modules

import pickle

To save the dictionary that we created as a pickle we do the following:

f = open("Madlib.pickle", 'wb')
pickle.dump(MadLibDict, f)
f.close()

We are creating a file for writing in binary format (that is what 'wb' means), then we dump our dictionary 'MadLibDict' into the file 'f'.  Finally we close the file that we opened for writing.

If we run the program again and get no errors then we successfully wrote the file.

Now that we have a file written to our hard drive, we can delete or comment out the declared MadLibDict in our code:

# MadLibDict = {
			  # "noun": ['dog-catcher', 'plum', 'golf ball'],	
			  # "adjective": ['ugly', 'fat', 'golden'],	
				# }

But we now need to open the file and extract the MadLibDict from it.  To do so we comment out the command to write the file and use some similar syntax to read it:

# f = open("Madlib.pickle", 'wb')
# pickle.dump(MadLibDict ,f)
# f.close()
f = open("Madlib.pickle", 'rb')
MadLibDict = pickle.load(f)
f.close()

Here 'rb' means read binary and now we define the vaiable name 'MadLibDict' as the result of loading the pickle file.

If we run the program a couple of times:

C:\PythonProject>python madlib.py
One day a ugly dog-catcher spoke to the dog and said...

C:\PythonProject>python madlib.py
One day a ugly dog-catcher spoke to the dog and said...

C:\PythonProject>python madlib.py
One day a golden plum spoke to the dog and said...

We get no errors!  The program reads the data from our pickle and can use it just as if we created it in the file.

To make this better, we would like to be able to add new words to our lists and store them.  We'll start by copying our 'getNewWord' definition but call it 'addNewWordToDict'.  We must pass into the definition the Dictionary that we want to add to.  And to see those changes, we must return the dictionary at the end of the definition.  If we don't return the dictionary when using the definition, any changes we make to it are not kept.

def addNewWordToDict(AnyDict, part_of_speech):
	query = "Give me an %s, and press 'Enter'." % part_of_speech
	engine.say(query, query)
	engine.runAndWait()
	newword = input()
	AnyDict[part_of_speech].append(newword)
	return AnyDict, newword

We technically don't need to return the 'newword' here but we can do so without incident as long as we have two variables waiting for assignment when we use this definition. 

Let's also make some simple definitions that will read the MadLibDict and write the MadLibDict:

def saveMadlibPickle(MadLibDict):
	f = open("Madlib.pickle", 'wb')	
	pickle.dump(MadLibDict, f)
	f.close()
	
def openMadlibPickle():	
	f = open("Madlib.pickle", 'rb')
	MadLibDict = pickle.load(f)
	f.close()
	return MadLibDict

Note that we pass the MadLibDict in when we want to save it (no return statement required), and we return the MadLibDict when we open it (with no argument required).

If we endeavour to use all of our new definitions, our code should now look like:

MadLibDict = openMadlibPickle()
MadLibDict, newword = addNewWordToDict(MadLibDict, "noun")
MadLibDict, newword = addNewWordToDict(MadLibDict, "noun")
MadLibDict, newword = addNewWordToDict(MadLibDict, "adjective")
MadLibDict, newword = addNewWordToDict(MadLibDict, "adjective")
saveMadlibPickle(MadLibDict)

Remember that the newword variable is not being used in this instance and we may clean it up later if we so choose.  Otherwise, this part of the code:

  1. Retrieves the MadLibDict from long-term storage
  2. Adds 2 nouns and 2 adjectives to the MadLibDict
  3. Saves the new MadLibDict

If we run the code:

C:\PythonProject>python madlib.py
Give me an noun, and press 'Enter'.
mouse
Give me an noun, and press 'Enter'.
shirt
Give me an adjective, and press 'Enter'.
blue
Give me an adjective, and press 'Enter'.
slimy
One day a fat mouse spoke to the dog and said...

And luckily our program used one of our newly added nouns and an old adjective thereby demonstrating that the dictionary has both old and new parts of speech stored in them.

 

skip_nextCustom Def #7: Search and Replace in Lines
  • Custom Def #1: Import pyttsx3

  • Custom Def #2: Read a story from lines.

  • Custom Def #3: Using Multiple Definitions

  • Custom Def #4: Generalized Definitions

  • Custom Def #5: Dictionaries and Definitions

  • Custom Def #6: Python Pickles
    (currently viewing)
  • Custom Def #7: Search and Replace in Lines

  • Custom Def #8: Now for the Story...