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)
다음 파일 대신 {} 표기법을 사용하여 작성된 파일 가져 오기에 대한 dicts (의 튜플을 사용
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 생성자를 사용하고 것 Dict 생성자가 가져 오기 전에 복제본이 사라집니다.).
파일에서 사전을로드하는 방법은 무엇입니까? –
@HughBothwell : with 'from x import dico' – Thammas