将键对值插入嵌套字典中,而不会在产生重复键的键定界符之后覆盖

insert key-pair value into nested dict without overwriting after delimiter of key which produce duplicate key

假设我有一个像这样的嵌套字典:

D={'Germany': {'1972-05-23': 'test1', '1969-12-27': 'test2'},
   'Morocco|Germany': {'1978-01-14':'test3'}}

我想要一个新的字典,例如:

{'Germany': {'1972-05-23': 'test1', '1969-12-27': 'test2', '1978-01-14':'test3'}
 'Morocco': {'1978-01-14':'test3'}}

这意味着我必须在 str.split(key) 之后处理可能重复的键,这是我的代码:

D={'Germany': {'1972-05-23': 'test1', '1969-12-27': 'test2'},
   'Morocco|Germany': {'1978-01-14':'test3'}}

new_dict={}
for item in D:
    for index in str.split(item,'|'):
        new_dict[index]=D[item]
print new_dict

然而拆分操作后生成的键值对覆盖了原来的结果:

{'Morocco': {'1978-01-14': 'test3'}, 'Germany': {'1978-01-14': 'test3'}}

我想知道如何修改我的代码以获得令人满意的指令以供进一步处理或针对此要求的任何更好的解决方案?

PS:我的 Python 版本是 2.7.12,Anaconda 4.0.0 通过 IDE PyCharm

任何帮助将不胜感激,谢谢

你可以使用:

if not index in new_dict: new_dict[index] = {}
new_dict[index].update(D[item])