編寫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