我有两个字典如下。
d1 = {
"user1":{"key1":"val1","key2":"val2"},
"user2":{"key3":"val3","key4":"val4"}
}
d2 = { "admin":{
"user1":{"key5":"val5","key6":"val6"},
"user3":{"key7":"val7","key8":"val8"}
}
}
最终字典应如下所示:
d3 = {
"user1":{"key1":"val1","key2":"val2","key5":"val5","key6":"val6"},
"user2":{"key3":"val3","key4":"val4"},
"user3":{"key7":"val7","key8":"val8"}
}
合并概念并不适用于此。你能帮帮我吗?
我已尝试过How to merge two Python dictionaries in a single expression?的解决方案。以下解决方案与我需要的不同。
{'admin': {'user3': {'key8': 'val8', 'key7': 'val7'}, 'user1': {'key6': 'val6',
'key5': 'val5'}}, 'user2': {'key3': 'val3', 'key4': 'val4'}, 'user1': {'key2': '
val2', 'key1': 'val1'}}
答案 0 :(得分:1)
您可以获取第一个字典的副本,然后迭代另一个 - 创建一个默认的空字典,然后使用d2的内容更新它,例如:
d3 = d1.copy()
for k, v in d2['admin'].iteritems():
d3.setdefault(k, {}).update(v)
为您输出:
{'user1': {'key1': 'val1', 'key2': 'val2', 'key5': 'val5', 'key6': 'val6'},
'user2': {'key3': 'val3', 'key4': 'val4'},
'user3': {'key7': 'val7', 'key8': 'val8'}}