Monday, 15 February 2010

Define a python dictionary with immutable keys but mutable values -



Define a python dictionary with immutable keys but mutable values -

well, question in title: how define python dictionary immutable keys mutable values? came (in python 2.x):

class fixeddict(dict): """ dictionary fixed set of keys """ def __init__(self, dictionary): dict.__init__(self) key in dictionary.keys(): dict.__setitem__(self, key, dictionary[key]) def __setitem__(self, key, item): if key not in self: raise keyerror("the key '" +key+"' not defined") dict.__setitem__(self, key, item)

but looks me (unsurprisingly) rather sloppy. in particular, safe or there risk of changing/adding keys, since i'm inheriting dict? thanks.

consider proxying dict instead of subclassing it. means methods define allowed, instead of falling 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 {} not defined.".format(key)) self._dictionary[key] = item def __getitem__(self, key): homecoming self._dictionary[key]

also, should utilize string formatting instead of + generate error message, since otherwise crash value that's not string.

python dictionary key immutability

No comments:

Post a Comment