Reputation: 107
Apologies if the question is amateurish, I'm new to classes/objects. I've looked through other Stack posts, and haven't gotten a clear answer to my question.
I want to initialize a class with an empty dictionary, and then add the keys/values to the dictionary. How would I do that?
Here is what I have now:
class Network(object):
self.dict = {}
def __init__(self, key, value):
"""
Initializes key and value of dictionary
"""
self.key = key
self.value = value
def add_key(key):
"""
Should add the key to the dictionary if it doesn't exist
"""
#if the key is not in the dictionary, add the key, and a value which is an empty list
if key not in self.dict:
self[key] = []
How would Python know that the key
and value
that I initialize are elements of the empty dictionary dict
I created?
EDIT: I updated the code according to Ghost Ops suggestion, but receiving an attribute error when I try to test it.
class Network(object):
def __init__(self, key, value):
"""
Initializes key and value of dictionary
"""
self.dicts = {}
self.key = key
self.value = value
def add_key(key):
"""
Should add the key to the dictionary if it doesn't exist
"""
#if the key is not in the dictionary, add the key, and a value which is an empty list
if key not in self.dicts:
self[key] = []
# to test if the code returns correctly:
def get_dicts(self):
return self.dicts
test_dic = {13: [1, 2, 3], 14:[4, 5]}
print(test_dic.get_dicts())
The error:
'dict' object has no attribute 'get_dicts'
Am I perhaps testing the code wrong?/ Apologies, I am very new to this
Upvotes: 4
Views: 5163
Reputation: 1644
You could inherit your class from dict
, basically your class will act as a dictionary too. Your add key
method would still work perfectly fine, just change self.dict
to self.keys()
to get all existing keys back. Key, and Value variables are unnecessary.
class Network(dict):
def __init__(self, key, value):
""" Initializes superclass """
super().__init__()
def add_key(key):
""" Should add the key to the dictionary if it doesn't exist """
if key not in self.keys():
self[key] = []
Upvotes: 2