c0ded_truth c0ded_truth - 1 month ago 7
Python Question

How do I access a dictionary from a function to be used in another function?

For an assignment I have to take a string as an input and write it as a file. Then, a function takes the string from the file and puts each word in a dictionary, with the value being the amount of times that word appears in the string. The words will then be printed in a "tower" (similar to a word cloud) with the size of each word based on the amount of times the word appears in the string.

These are the two important functions:

def word_freq_dict(): # function to count the amount of times a word is in the input string
file = open("data_file.txt", 'r')
readFile = file.read() #reads file
words = readFile.split() #splits string into words, puts each word as an element in a list
word_dict = {} # empty dictionary for words to be placed in with the amount of times they appear
for i in words:
word_dict[i] = word_dict.get(i,0) + 1 # adds items in "words" to a dictionary and amount of times they appear

return word_dict


and

def word_tower():
t = turtle.Turtle()
t.hideturtle() # hides cursor
t.up() # moves cursor up
t.goto(-200, -200) # starts at the -200,-200 position
word_freq_dict() #calls dictionary function
for key, value in word_dict.items():
t.write(key, font = ('Arial', value*10, 'normal'))
t.up(1.5*len(key))


Let me explain the second function. I have imported turtle graphics for the tower to be formed. What I tried to do is call the word_freq_dict function into the word_tower function in order to get access to the dictionary. The reason for this is because the word has to be printed 10 times the size of the amount of times it appears in the string. The cursor then must move up 1.5 times the size of the word.

After running, the error that I get is that word_dict was not defined in the word_tower function, which I assume is because it's a local variable. How can I access it?

Answer

Calling a function doesn't automatically save anything in your current namespace. You have to explicitly assign it.

word_dict = word_freq_dict()
Comments