-3

I've two dictionaries as below.

d1 = {
       "user1":{"key1":"val1","key2":"val2"},
       "user2":{"key3":"val3","key4":"val4"}
     }

d2 = { "admin":{
      "user1":{"key5":"val5","key6":"val6"},
      "user3":{"key7":"val7","key8":"val8"}
                }
     }

Final dictionary should look like this:

d3 = {
              "user1":{"key1":"val1","key2":"val2","key5":"val5","key6":"val6"},
              "user2":{"key3":"val3","key4":"val4"},
               "user3":{"key7":"val7","key8":"val8"}
              }

Merging concept doesn't apply here. Could you please help me here ?

I've tried the solution of How to merge two Python dictionaries in a single expression? . Below solution is different from what i needed.

{'admin': {'user3': {'key8': 'val8', 'key7': 'val7'}, 'user1': {'key6': 'val6',
'key5': 'val5'}}, 'user2': {'key3': 'val3', 'key4': 'val4'}, 'user1': {'key2': '
val2', 'key1': 'val1'}}
Community
  • 1
  • 1
User
  • 93
  • 1
  • 1
  • 9

1 Answers1

1

You can take a copy of the first dictionary, then iterate over the other - creating a default empty dictionary, then updating it with the contents of d2, eg:

d3 = d1.copy()
for k, v in d2['admin'].iteritems():
    d3.setdefault(k, {}).update(v)

Gives you output of:

{'user1': {'key1': 'val1', 'key2': 'val2', 'key5': 'val5', 'key6': 'val6'},
 'user2': {'key3': 'val3', 'key4': 'val4'},
 'user3': {'key7': 'val7', 'key8': 'val8'}}
Jon Clements
  • 138,671
  • 33
  • 247
  • 280