Mutable dictionary with fixed and ordered keys

I use OrderedDict to store some important data. I want to make sure that a randomly inserted new key in this dictionary throws an exception, but I want the dict to be changed . I want the keys to be fixed (after creating in __init__). Can this be done using some library class? Or do I need to somehow implement a new ordered class for this?

Example:

d = FixedOrderedDict( ( ("A", 1), ("B", 2) ) )

print d["A"]
# 1
d["A"] = 11
print d["A"]
# 11
d["C"] = 33
# throws exception

I was asked to find a solution called FrozenDict , but it makes the dict read-only - the values ​​cannot be changed (throws an exception when assigning new values). This is not what I want to achieve.

+4
2

( ). collections.MutableMapping (collections.abc.MutableMapping 3.3 ), . , , :

from collections import MutableMapping, OrderedDict

class FixedOrderedDict(MutableMapping):
    def __init__(self, *args):
        self._d = OrderedDict(*args)

    def __getitem__(self, key):
        return self._d[key]

    def __setitem__(self, key, value):
        if key not in self._d:
            raise KeyError("Must not add new keys")
        self._d[key] = value

    def __delitem__(self, key):
        raise NotImplementedError("Must not remove keys")

    def __iter__(self):
        return iter(self._d)

    def __len__(self):
        return len(self._d)
+4

dict, - , ? , .

from collections import OrderedDict

class FreezableDict(OrderedDict):
    def __init__(self, *args, **kw):
        super(OrderedDict, self).__init__(*args, **kw)
        self._frozen = False
    def __setitem__(self, key, value):
        if key not in self and self._frozen:
            raise TypeError("No key additions once a FreezableDict is frozen!")
        return super(OrderedDict, self).__setitem__(key, value)
    def freeze(self):
        self._frozen = True

d = FreezableDict((("A", 1), ("B", 2)))

print d["A"]
d["C"] = "New Value"
d.freeze()
d["C"] = "Replacement"
print d["C"]
d["D"] = "This raises a TypeError exception"

, , , , OrderedDict - , . , .

+1

Source: https://habr.com/ru/post/1548517/


All Articles