User User - 3 months ago 6
Python Question

How to club dictionaries?

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 can I 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'}}

Answer

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'}}
Comments