Skip to content Skip to sidebar Skip to footer

I Want To Subclass Dict And Set Default Values

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

Solution 1:

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

Solution 2:

No subclassing needed:

def predefined_dict(**kwargs):
    d = {
        'key1': 'stuff',
        ...
    }
    d.update(kwargs)
    return d

new_dict = predefined_dict()
print new_dict['key1']

or just:

defaults = {'a':1, 'b':2}
new_dict = defaults.copy()
print new_dict['a']

Solution 3:

@astynax provided a good answer but if you must use a subclass you could:

class defaultattrdict(dict):
    def __missing__(self, key):
        try: return getattr(self, key)
        except AttributeError:
            raise KeyError(key) #PEP409 from None

Then:

class NewDict(defaultattrdict):
    Key1 = "stuff"
    Key2 = "Other stuff"
    NoList = []
    Nada = None

PrefilledDict = NewDict()
print(PrefilledDict['Key1']) # -> "stuff"
print(PrefilledDict.get('Key1')) #NOTE: None as defaultdict

Note: your code doesn't follow pep8 naming convention.


Post a Comment for "I Want To Subclass Dict And Set Default Values"