Reputation: 16469
I've got a main function in my python code and several other functions. In my main, I've accessed another function that creates a dictionary. At the end of my python code is an if statement that writes text into a text file. I'm having trouble figuring out how to access the dictionary created from the previous functions.
Here is a model of how my code currently works
def main:
# "does something"
call function X
# does other stuff
def X:
#create dictionary
dict = {'item1': 1,'item2': 2}
return dictionary
....
.... # other functions
....
if __name__ == "__main__":
# here is where I want to write into my text file
f = open('test.txt','w+')
main()
f.write('line 1: ' + dict[item1])
f.write('line 2: ' + dict[item2])
f.close()
I'm just starting to learn python so any help is much appreciated! Thank you!
Upvotes: 0
Views: 108
Reputation: 59984
You have to add parentheses ()
when defining functions, even if it does not take any arguments:
def main():
...
def X():
...
Also, because X()
returns something, you have to assign the output to a variable. So you can do something like this in main
:
def main():
mydict = X()
# You now have access to the dictionary you created in X
You can then return mydict
if you want in main(), so you can use it at the end of your script:
if __name__ == "__main__":
f = open('test.txt','w+')
output = main() # Notice how we assign the returned item to a variable
f.write('line 1: ' + output[item1]) # We refer to the dictionary we just created.
f.write('line 2: ' + output[item2]) # Same here
f.close()
You can not define a variable in a function and then use it elsewhere outside of the function. The variable will only be defined in the local scope of the relative function. Thus, returning it is a good idea.
By the way, it's never a good idea to name a dictionary dict
. It will override the built-in.
Upvotes: 2