MachineLearner
MachineLearner

Reputation: 977

Combine two nested dictionaries with same keys but different dictionaries as values

I have two dictionaries (see code example) with nested dictionaries as values. I want to join both dictionaires such that I obtain one single dictionary with added key value pairs in the nested dictionairy.

My current code works but it does not seem DRY (don't repeat yourself) to me. What is the most pyhtonic way to solve this problem?

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

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

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

print(dictionary_base)

Desired output should look like

{'anton': {'address': '12120 New York',
           'age': 29,
           'job': 'doctor',
           'name': 'Anton'},
 'bella': {'address': '13413 Washington',
           'age': 21,
           'job': 'lawyer',
           'name': 'Bella'}}

Upvotes: 2

Views: 57

Answers (2)

kederrac
kederrac

Reputation: 17322

you could use a dictionary comprehension:

{k: {**dictionary_base[k], **dictionary_extension[k]} for k in dictionary_base}

output:

{'anton': {'name': 'Anton',
  'age': 29,
  'job': 'doctor',
  'address': '12120 New York'},
 'bella': {'name': 'Bella',
  'age': 21,
  'job': 'lawyer',
  'address': '13413 Washington'}}

Upvotes: 1

Rakesh
Rakesh

Reputation: 82765

Use 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)

Output:

{'anton': {'address': '12120 New York',
           'age': 29,
           'job': 'doctor',
           'name': 'Anton'},
 'bella': {'address': '13413 Washington',
           'age': 21,
           'job': 'lawyer',
           'name': 'Bella'}}

Upvotes: 3

Related Questions