Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating dictionaries with pre-defined keys

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?

like image 892
Levi Campbell Avatar asked Nov 28 '22 05:11

Levi Campbell


2 Answers

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
like image 149
Ryan Ginstrom Avatar answered Dec 05 '22 02:12

Ryan Ginstrom


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.

like image 22
Paolo Bergantino Avatar answered Dec 05 '22 03:12

Paolo Bergantino