编写dict的子类,覆盖__setitem__,以便在替换现有密钥时引发错误;重写该文件以使用新的子类的构造函数而不是默认的dict内置函数。
import collections
class Dict(dict):
def __init__(self, inp=None):
if isinstance(inp,dict):
super(Dict,self).__init__(inp)
else:
super(Dict,self).__init__()
if isinstance(inp, (collections.Mapping, collections.Iterable)):
si = self.__setitem__
for k,v in inp:
si(k,v)
def __setitem__(self, k, v):
try:
self.__getitem__(k)
raise ValueError("duplicate key '{0}' found".format(k))
except KeyError:
super(Dict,self).__setitem__(k,v)
那么你的文件将有被写成使用的,而不是对文件导入类型的字典(使用{}符号写成的元组
dico = Dict(
('root', Dict(
('a', Dict(
('some_key', 'value'),
('another_key', 'another_value')
),
('b', Dict(
('some_key', 'value')
),
('c', Dict(
('some_key', 'value'),
('another_key', 'another_value')
),
....
)
)
,它会使用默认的字典构造函数和在Dict构造函数获得它们之前,重复项会消失!)。
你是如何从文件加载字典? – 2011-02-15 01:59:27
@HughBothwell:用`from x import dico` – Thammas 2011-02-15 02:35:12