Define a python dictionary with immutable keys but mutable values

前端 未结 3 1725
陌清茗
陌清茗 2021-01-04 10:04

Well, the question is in the title: how do I define a python dictionary with immutable keys but mutable values? I came up with this (in python 2.x):

class Fi         


        
3条回答
  •  醉话见心
    2021-01-04 10:47

    Consider proxying dict instead of subclassing it. That means that only the methods that you define will be allowed, instead of falling back to dict's implementations.

    class FixedDict(object):
            def __init__(self, dictionary):
                self._dictionary = dictionary
            def __setitem__(self, key, item):
                    if key not in self._dictionary:
                        raise KeyError("The key {} is not defined.".format(key))
                    self._dictionary[key] = item
            def __getitem__(self, key):
                return self._dictionary[key]
    

    Also, you should use string formatting instead of + to generate the error message, since otherwise it will crash for any value that's not a string.

提交回复
热议问题