Linking Dictionary Values
Jeff Shannon
jeff at ccvcorp.com
Fri Aug 24 14:49:16 EDT 2001
"Maan M. Hamze" wrote:
> Is it possible to link Dictionary values of each key into a text file? So
> the value of a key is a text file somewhere on the PC. And if so, how do I
> instruct Python to open the text file and print into screen when the key of
> the text file is used?
> Also, is it possible to link a value of a Dictionary key into a Python
> function/procedure? So, if the key is encountered, a way for the
> functionprocedure to be run.
> Maan
First case:
class FileDict:
def __init__(self):
self.files = {}
def AddFile(self, key, filename)
self.files[key] = filename
def GetFile(self, key):
try:
fp = open(self.files[key], 'r')
except KeyError:
print "Error! No such file registered!"
return None
text = fp.read()
fp.close()
return text
Of course, you might want to add some code to verify that the filename you're
being fed exists, is a valid (fully qualified) path, etc, etc...
Second case:
def test1():
print "Testing!"
def test2():
print "But I don't like spam!"
FuncDict = { "first" : test1, "second" : test2 }
>>> FuncDict['first']()
Testing!
>>> FuncDict['second']()
But I don't like spam!
More information about the Python-list
mailing list