[Tutor] Using a dictionary to map functions

Colby Christensen colbychristensen at hotmail.com
Tue Apr 26 00:30:38 EDT 2016


I am a novice self taught programmer learning with Python. I am working on a program to calculate coordinate geometry. The input file is a list of commands. A number is assigned to each command and followed by various inputs required to make the calculation. The input has the following format:

5 201 1496.0423 1234.5678 (this command stores the last two numbers as the coordinates for point 201; 5 = store point command)
comments lines begin with #

Each command can take 3 to 7 arguments depending on the calculation. 

Currently I am building each command as a separate module that I can import into the main program. My main program reads the input file and separates the commands from blank and comment lines. As it reads the input file, it splits the command and appends it to a list. I'm thinking of having a dictionary that maps the commands/functions to each number. My conundrum is how to use the dictionary mapping to call the functions and pass the arguments.

In the case below, I would pass the arguments pt_table and line. In the function store_point, I break the list, line, into components to make the calculation. By passing the entire line, I can validate the command in the corresponding function. 

import re
from store_point import store_point

try:
    infile = open(raw_input("Enter input file name; name.txt:"),'r')
except:
    print "Invalid filename"
    exit()

templist = []
pt_table = {}
cmd_table = {5:"store_point", 19: "line_line_int"}
count = 0

for line in infile:
    #print line
    line = line.rstrip()
    if re.search('^[0-9]+', line):
        a = line.split()
        templist.append(a)

for line in templist:
    #use dictionary to call and pass arguments to function

As a novice programmer, I am also open to suggestions to do this more effectively. 
Thank you
Colby 		 	   		  


More information about the Tutor mailing list