問題描述
如果用戶在字典中輸入重復鍵,我會嘗試引發錯誤.字典在一個文件中,用戶可以手動編輯該文件.
I try to raise an error if the user enter a duplicate key in a dictionary. The dictionary is in a file and the user can edit the file manually.
例子:
dico= {'root':{
'a':{'some_key':'value',...},
'b':{'some_key':'value',...},
'c':{'some_key':'value',...},
...
'a':{'some_key':'value',...},
}
}
新鍵a"已經存在...
the new key 'a' already exist...
當我從文件中加載 dico 時,如何測試 dico 并警告用戶?
How can I test dico and warn the user when I load dico from the file?
推薦答案
寫一個dict的子類,覆蓋__setitem__,這樣在替換現有key時會拋出錯誤;重寫文件以使用新子類的構造函數而不是默認的 dict 內置函數.
Write a subclass of dict, override __setitem__ such that it throws an error when replacing an existing key; rewrite the file to use your new subclass's constructor instead of the default dict built-ins.
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')
),
....
)
)
使用元組而不是字典來導入文件(使用 {} 表示法編寫,它將使用默認的字典構造函數,并且重復項會在字典構造函數獲取它們之前消失!).
using tuples instead of dicts for the file import (written using the {} notation, it would use the default dict constructor, and the duplicates would disappear before the Dict constructor ever gets them!).
這篇關于如果字典中的鍵重復,如何引發錯誤的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!