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
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_dictionary
and the values will be accessible in main()
. In your case you are creating a new dictionary in init_dictionary
with the line sunspot_dict = {}
. You don't want to do this, because the dictionary you want to use was already created in main()
.
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
.
Given the restriction you give in your reply to Raymond, that you can't modify the init_dictionary()
method and that it requires that you pass it a dictionary which it will then populate, I recommend that you make your own class a subclass of dict
.
class MySunspotDict(dict):
def __init__(self, file_str):
init_dictionary(file_str, self)
# ... define your other methods here
sunspot_dict = MySunspotDict(file_str)
The sunspot_dict = MySunspotDict(file_str)
line goes where you currently have init_dictionary(file_str, sunspot_dict)
, so your existing file_str
is passed to the MySunspotDict
constructor (__init__()
method), which will then pass it to init_dictionary()
.
The init_dictionary()
call works the same as the one you already have, except it passes the new object rather than an empty dict
to the function that populates the dictionary. Since your new class is derived from dict
, i.e. it is a subclass, it works just like a regular dictionary for this purpose. So what you have is basically a dict
that you can attach your own methods to. (You can also override some of the standard dictionary behavior by defining methods with special names, but you shouldn't need to do that in this case.)
Note that in your methods, self
will be the dictionary -- you don't need to create the dictionary in your __init__()
and store it as an attribute of your class (you will see this pattern in a lot of Python code). The dictionary already exists by the time __init__()
runs.