那么问题是在标题中:我如何用不可变键定义一个
Python字典,但是可变值?我想出了这个(在python 2.x中):
class FixedDict(dict):
"""
A dictionary with a fixed set of keys
"""
def __init__(self, dictionary):
dict.__init__(self)
for 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+"' is not defined")
dict.__setitem__(self, key, item)
但它看起来对我来说(毫不奇怪)相当马虎.特别是,这是安全的还是有实际改变/添加一些密钥的风险,因为我是继承自?
谢谢.