Example 1-1. PP4E\Preview\initdata.py
initialize data to be stored in files, pickles, shelves
records
bob = {'name': 'Bob Smith', 'age': 42, 'pay': 30000, 'job': 'dev'}
sue = {'name': 'Sue Jones', 'age': 45, 'pay': 40000, 'job': 'hdw'}
tom = {'name': 'Tom', 'age': 50, 'pay': 0, 'job': None}
database
db = {}
db['bob'] = bob
db['sue'] = sue
db['tom'] = tom
if name == 'main': # when run as a script
for key in db:
print(key, '=>\n ', db[key])
As usual, the name test at the bottom of Example 1-1 is true only when this file is
run, not when it is imported. When run as a top-level script (e.g., from a command
line, via an icon click, or within the IDLE GUI), the file’s self-test code under this test
dumps the database’s contents to the standard output stream (remember, that’s what
print function-call statements do by default).
Here is the script in action being run from a system command line on Windows. Type
the following command in a Command Prompt window after a cd to the directory where
the file is stored, and use a similar console window on other types of computers:
...\PP4E\Preview> python initdata.py
bob =>
{'job': 'dev', 'pay': 30000, 'age': 42, 'name': 'Bob Smith'}
sue =>
{'job': 'hdw', 'pay': 40000, 'age': 45, 'name': 'Sue Jones'}
tom =>
{'job': None, 'pay': 0, 'age': 50, 'name': 'Tom'}
File name conventions
Since this is our first source file (a.k.a. “script”), here are three usage notes for this
book’s examples:
- The text ...\PP4E\Preview> in the first line of the preceding example listing stands
for your operating system’s prompt, which can vary per platform; you type just the
text that follows this prompt (python initdata.py). - Like all examples in this book, the system prompt also gives the directory in the
downloadable book examples package where this command should be run. When
running this script using a command-line in a system shell, make sure the shell’s
current working directory is PP4E\Preview. This can matter for examples that use
files in the working directory.
Step 2: Storing Records Persistently | 15