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

时间:2020-11-03 06:22:48

标签: 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

1 个答案:

答案 0 :(得分:2)

您可以尝试以下操作:

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

它将在您想要的地方插入新词典。

相关问题