So, I always thought that it was possible to return dictionaries in Python. I was wanting to do this because I would prefer not to use globals. However, I am having trouble with returning my dictionary.
Code:
#!/usr/bin/python
# 6/9/09
def loadWords():
pathstart = "/home/foo/Documents/PyScripts/Vocab/Lists/"
print "What is the number of the list you would like to load?"
listnum = raw_input("> ")
fn = 'VocabList.'+str(listnum)+'.txt'
fullpath = pathstart + fn
wordfile=open(fullpath,"r")
words = {}
for i in wordfile:
p=i.split(":")
first = p[0]
second = p[1]
words[first] = second
print "Print test one..."
for x in words:
print x
return words
loadWords()
print "Done loading words."
print
print "Print test two..."
print
for x in words:
print x,
print "Done printing words."
If it matters, this is what my "VocabList.0.txt" file looks like:
uno:one
dos:two
tres:three
cuatro:four
cinco:five
Also, the output of running my script is the following:
What is the number of the list you would like to load?
> 0
Print test one...
cuatro
dos
tres
cinco
uno
Done loading words.Print test two...
Traceback (most recent call last):
File "./VocabTest.Revamp.py", line 27, in <module>
for x in words:
NameError: name 'words' is not defined
So, what could I do to allow myself to print the "words" dictionary out of the function "loadWords"?
Thanks in advance.