Python 如何将新词典插入嵌套词典的最深层?
假设有一本字典,如下所示。当我得到一本新字典时,我想把它插入最深层Python 如何将新词典插入嵌套词典的最深层?,python,Python,假设有一本字典,如下所示。当我得到一本新字典时,我想把它插入最深层 d = { 'text': 'Layer 0', 'child': { 'text': 'Layer 1', 'child': { 'text': 'Layer 2', 'sibling': { 'text': 'Layer 3', } } } } ne
d = {
'text': 'Layer 0',
'child': {
'text': 'Layer 1',
'child': {
'text': 'Layer 2',
'sibling': {
'text': 'Layer 3',
}
}
}
}
new_dict = {
'text': 'Layer 4',
}
d['child']['child']['sibling']['child'] = new_dict
这是我的代码,但调用两次后,它将覆盖字典的第二层。如何将新词典插入嵌套词典的最深层
def nested(current_dict, new_dict, name):
for key in ('child', 'sibling'):
if key in current_dict:
current_dict = nested(current_dict[key], new_dict, name)
else:
current_dict[name] = new_dict
return current_dict
您可以尝试以下方法:
def嵌套(当前目录、新目录、名称):
按键输入=无
对于输入项(“子项”、“兄弟项”):
如果输入当前命令:
按键输入按键=按键
打破
如果dict中的键不是None:
嵌套(当前目录[目录中的键]、新目录、名称)
其他:
当前目录[名称]=新目录
它将在您需要的地方插入新词典。在您的案例中,一个原子词典总共可以有多少个键?3.(text,child,sibling)还有,名称是什么?@Ragnar它接受3个键(text,child,sibling),但child和sibling不会存在于同一层。如果当前层中没有子字典和同级字典,则新字典将添加到子字典。谢谢。这是否意味着它将在同一层中同时拥有孩子或兄弟姐妹,但不能同时拥有两个?@Ragnar是的,是的。@kolin,这是否为您提供了所需的输出?如果是这样,那么你可以接受这个答案。