Mutable dictionary with fixed and ordered keys

dictionary, python

Solution

I'm not aware of such a solution in the standard library (it's a rather specialized use case). You can however use `collections.MutableMapping` (`collections.abc.MutableMapping` in 3.3 and onwards) to get most functionality for free. Give or take a few minor issues I may be overlooking right now, it's just:

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)

Problem

I am using OrderedDict for storage of some important data. I want to ensure, that accidentally inserted new key to this dictionary throws an exception but I want dict to be mutable. I want keys to be fixed (after created in `__init__`). Is it possible to do that with some library class? Or do I have to somehow implement 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 recommended to look up solution called FrozenDict but it makes dict read-only - values cannot be modified (throws exception when assigning new values). This is not what I want to achieve.

Original source