I have a file that I’m working with. I want to create a function that reads the files and place the contents into a dictionary. Then that dictionary needs to be passed through the main function. Here is the main program. It cannot be changed. Everything I do must work with the main program.
def main():
sunspot_dict = {}
file_str = raw_input("Open what data file: ")
keep_going = True
while keep_going:
try:
init_dictionary(file_str, sunspot_dict)
except IOError:
print "Data file error, try again"
file_str = raw_input("Open what data file: ")
continue
print "Jan, 1900-1905:", avg_sunspot(sunspot_dict, (1900,1905),(1,1))
print "Jan-June, 2000-2011:", avg_sunspot(sunspot_dict, (2000,2011), (1,6))
print "All years, Jan:", avg_sunspot(sunspot_dict, month_tuple=(1,1))
print "All months, 1900-1905:", avg_sunspot(sunspot_dict, year_tuple=(1900,1905))
try:
print "Bad Year Key example:", avg_sunspot(sunspot_dict, (100,1000), (1,1))
except KeyError:
print "Bad Key raised"
try:
print "Bad Month Index example:", avg_sunspot(sunspot_dict, (2000,2011), (1,100))
except IndexError:
print "Bad Range raised"
keep_going = False
print "Main function finished normally."
print sunspot_dict
Here is what I have so far:
def init_dictionary(file_str, sunspot_dict):
line = open(file_str, "rU")
sunspot_dict = {}
for i in line:
sunspot_dict[i]
print sunspot_dict
Based on your second comment and your preview code, you are on the right track. Dictionaries in Python are passed by reference, so you should just be able to fill the dictionary provided to
init_dictionaryand the values will be accessible inmain(). In your case you are creating a new dictionary ininit_dictionarywith the linesunspot_dict = {}. You don’t want to do this, because the dictionary you want to use was already created inmain().At this point we would need to know the format of the file you are reading. Basically you need to open the file, then probably read it line by line while parsing the lines into key/value pairs and filling
sunspot_dict.