合并两个嵌套字典,它们具有相同的键,但字典的值不同

问题描述 投票:0回答:1

我有两个字典(请参见代码示例),其中嵌套的字典为值。我想同时加入两个字典,以便在嵌套字典中获得一个带有附加键值对的单个字典。

我当前的代码有效,但对我来说似乎不干(不要重复)。解决这个问题的最方法是什么?

dictionary_base = {
  'anton': {
    'name': 'Anton',
    'age': 29,
  },
  'bella': {
    'name': 'Bella',
    'age': 21,
  },
}

dictionary_extenstion = {
  'anton': {
    'job': 'doctor',
    'address': '12120 New York',
  },
  'bella': {
    'job': 'lawyer',
    'address': '13413 Washington',
  },
}

for person in dictionary_base:
  dictionary_base[person]['job'] = dictionary_extenstion[person]['job']
  dictionary_base[person]['address'] = dictionary_extenstion[person]['address']

print(dictionary_base)

所需的输出应该看起来像

{'anton': {'address': '12120 New York',
           'age': 29,
           'job': 'doctor',
           'name': 'Anton'},
 'bella': {'address': '13413 Washington',
           'age': 21,
           'job': 'lawyer',
           'name': 'Bella'}}
python dictionary dry
1个回答
2
投票

使用dict.update

Ex:

dictionary_base = {
  'anton': {
    'name': 'Anton',
    'age': 29,
  },
  'bella': {
    'name': 'Bella',
    'age': 21,
  },
}

dictionary_extenstion = {
  'anton': {
    'job': 'doctor',
    'address': '12120 New York',
  },
  'bella': {
    'job': 'lawyer',
    'address': '13413 Washington',
  },
}

for person in dictionary_base:
    dictionary_base[person].update(dictionary_extenstion[person])

print(dictionary_base)

输出:

{'anton': {'address': '12120 New York',
           'age': 29,
           'job': 'doctor',
           'name': 'Anton'},
 'bella': {'address': '13413 Washington',
           'age': 21,
           'job': 'lawyer',
           'name': 'Bella'}}
© www.soinside.com 2019 - 2024. All rights reserved.