I want to subclass dict and set default values
dictionary, python, subclass
Solution
You can achieve what you want as such:
class NewDict(dict):
def __init__(self):
self['Key1'] = 'stuff'
...
PrefilledDict = NewDict()
print PrefilledDict['Key1']
With your code, you are creating attributes of the NewDict class, not keys in the dictionary, meaning that you would access the attributes as such:
PrefilledDict = NewDict()
print PrefilledDict.Key1
Problem
I have a need to create a special subclass of dict. In it I want to set default values for a set of keys. I seem to be failing in finding the correct syntax to do this. Here is what I have been trying: ``` class NewDict(dict): Key1 = "stuff" Key2 = "Other stuff" NoList = [] Nada = None ``` I am then instantiating an object like this: ``` PrefilledDict = NewDict() ``` and trying to use something in there: ``` print PrefilledDict['Key1'] ``` But it seems that my dictionary is not a dictionary. What little bit am I missing?