Immutable dictionary, only use as a key for another dictionary

前端 未结 8 2304
情歌与酒
情歌与酒 2020-12-05 04:52

I had the need to implement a hashable dict so I could use a dictionary as a key for another dictionary.

A few months ago I used this implementation: Python hashable

相关标签:
8条回答
  • 2020-12-05 05:26

    You can use an enum:

    import enum
    
    KeyDict1 = enum.Enum('KeyDict1', {'InnerDictKey1':'bla', 'InnerDictKey2 ':2})
    
    d = { KeyDict1: 'whatever', KeyDict2: 1, ...}
    

    You can access the enums like you would a dictionary:

    KeyDict1['InnerDictKey2'].value  # This is 2
    

    You can iterate over the names, and get their values... It does everything you'd expect.

    0 讨论(0)
  • 2020-12-05 05:29

    The Mapping abstract base class makes this easy to implement:

    import collections
    
    class ImmutableDict(collections.Mapping):
        def __init__(self, somedict):
            self._dict = dict(somedict)   # make a copy
            self._hash = None
    
        def __getitem__(self, key):
            return self._dict[key]
    
        def __len__(self):
            return len(self._dict)
    
        def __iter__(self):
            return iter(self._dict)
    
        def __hash__(self):
            if self._hash is None:
                self._hash = hash(frozenset(self._dict.items()))
            return self._hash
    
        def __eq__(self, other):
            return self._dict == other._dict
    
    0 讨论(0)
提交回复
热议问题