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
self.dict = {}line into the__init__function so that for every initiation, it creates a new dictionary and also, name the dictionary with an another name likeself._dictnotdict