将密钥对值插入到嵌套的dict中,而不会在生成重复密钥的密钥分隔符后覆盖

时间:2016-09-16 13:23:12

标签: python dictionary split overwrite

假设我有一个嵌套的词典,如:

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

我想知道如何修改我的代码以获得令人满意的dict进行进一步处理或更好地解决此要求?

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

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

1 个答案:

答案 0 :(得分:2)

你可以使用:

cassandra.yaml
相关问题