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
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.