In python, is there a way to create a class that is treated like a dictionary but have the keys pre-defined when a new instance is created?
You can also have the dict subclass restrict the keys to a predefined list, by overriding __setitem__()
>>> class LimitedDict(dict):
_keys = "a b c".split()
def __init__(self, valtype=int):
for key in LimitedDict._keys:
self[key] = valtype()
def __setitem__(self, key, val):
if key not in LimitedDict._keys:
raise KeyError
dict.__setitem__(self, key, val)
>>> limited = LimitedDict()
>>> limited['a']
0
>>> limited['a'] = 3
>>> limited['a']
3
>>> limited['z'] = 0
Traceback (most recent call last):
File "<pyshell#61>", line 1, in <module>
limited['z'] = 0
File "<pyshell#56>", line 8, in __setitem__
raise KeyError
KeyError
>>> len(limited)
3
You can easily extend any built in type. This is how you'd do it with a dict:
>>> class MyClass(dict):
... def __init__(self, *args, **kwargs):
... self['mykey'] = 'myvalue'
... self['mykey2'] = 'myvalue2'
...
>>> x = MyClass()
>>> x['mykey']
'myvalue'
>>> x
{'mykey2': 'myvalue2', 'mykey': 'myvalue'}
I wasn't able to find the Python documentation that talks about this, but the very popular book Dive Into Python (available for free online) has a few examples on doing this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With