Write a subclass of dict, override __setitem__ so that it throws an error when replacing an existing key; rewrite the file to use your new subclass constructor instead of the built-in dict built-in modules.
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)
then your file should be written as
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') ), .... ) )
using tuples instead of dicts to import the file (written using the {} notation, it will use the default dict constructor, and duplicates will disappear before the Dict constructor ever gets them!).
Hugh bothwell
source share