爲了得到一個遞歸的字典,你可以使用這個輔助類
class RecursiveDict(dict):
def __missing__(self, attr):
db = RecursiveDict()
super(RecursiveDict, self).__setitem__(attr, db)
return db
def __setitem__(self, attr, value):
if isinstance(attr, (tuple,list)):
cur = self[attr[0]]
for i in attr[1:-1]:
cur = cur[i]
cur[attr[-1]] = value
else:
super(RecursiveDict, self).__setitem__(attr, value)
def __getitem__(self, item):
if isinstance(item, (tuple, list)):
cur = self[item[0]]
for i in item[1:]:
cur = cur[i]
return cur
else:
return super(RecursiveDict, self).__getitem__(item)
def __delitem__(self, item):
if isinstance(item, (tuple, list)):
cur = self[item[0]]
for i in item[1:-1]:
cur = cur[i]
del cur[item[-1]]
else:
return super(RecursiveDict, self).__delitem__(item)
使用像:
a=RecursiveDict()
path="https://stackoverflow.com/a/a/a"
path = path.strip("/").split("/")
a[path]="value"
a["a","b","c"]=1
a["b"]=2
print a
- >{'a': {'a': {'a': 'value'}, 'b': {'c': 1}}, 'b': 2}
這似乎是一所學校分配。你可以分享你迄今爲止嘗試過的嗎? –
似乎喜歡它,但我認爲這就是我提出問題的方式,我幾乎刪除了所有的上下文。實際情況是,我看不到任何有關這個挑戰的問題,因此認爲值得補充。 – GMeister
你所要做的就是使用遞歸/實現一個自定義類 – muddyfish