替换python字典中的key值

转自:http://blog.csdn.net/jt674106399/article/details/76516186

比如有一个

a = {‘a’: 1}

希望变为

a = {‘b’ :1}

即:在保留value不变的情况下,替换key值

目前能想到的实现方案是

a[‘b’] = a.pop(‘a’)

 

扩展:

patient={'a.a':{'b.b':{'c.c':{'d.d':'end', 'e.e':'end1'}}, 'y.y':{'m.m':{'n.n':'end'}}}, 'z.z':'haha'}

多层嵌套的字典,使用递归函数解决

def replace_dot(patient):

    for key in patient.keys():

        if isinstance(patient[key], dict):

            patient[key] = replace_dot(patient[key])

        newkey = key.replace('.', '+')

        patient[newkey] = patient.pop(key)

    return patient

---------------------------------------------------------------------------------

关注微信公众号即可在手机上查阅,并可接收更多测试分享~

原文地址:https://www.cnblogs.com/songzhenhua/p/9312714.html