转自: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

 

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

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

替换python字典中的key值

相关文章:

  • 2021-07-02
  • 2022-12-23
  • 2022-12-23
  • 2022-02-20
  • 2022-12-23
  • 2021-07-16
  • 2021-05-15
  • 2021-06-30
猜你喜欢
  • 2022-12-23
  • 2023-03-22
  • 2022-12-23
  • 2022-12-23
  • 2021-04-27
相关资源
相似解决方案