如何将新词典插入嵌套词典的最深层

  • 本文关键字:嵌套 新词典 插入 python
  • 更新时间 :
  • 英文 :


假设有一个字典如下。当我得到一本新字典时,我想把它插入最深层次。

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 nested(current_dict, new_dict, name):
key_in_dict = None
for key in ('child', 'sibling'):
if key in current_dict:
key_in_dict = key
break
if key_in_dict is not None:
nested(current_dict[key_in_dict], new_dict, name)
else:
current_dict[name] = new_dict

它会把你的新字典插入你想要的地方。

最新更新