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.

Recommended Answers

All 3 Replies

loadWords()

This is your problem. While the function actually returns the dictionary, you're never actually "catching" with anything. You should be doing something like this:

my_results = loadWords()

Then the variable my_results will contain whatever object is passed back from the function loadWords()

commented: Always helps and is very thorough. +1

Well, that was a great deal easier than I thought it would be. Thank you for catching my stupid mistake. And also, it seems like every time I post on this forum you always seem to be the one to solve my problems. Thank you again!

Well, that was a great deal easier than I thought it would be. Thank you for catching my stupid mistake. And also, it seems like every time I post on this forum you always seem to be the one to solve my problems. Thank you again!

Eh, that's just because I frequently take breaks from my work to let my mind relax... for some reason relaxing means trolling these forums :\

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.