如何在字典中添加双引号? [英] How to add double quotes to the dictionary?

查看:380
本文介绍了如何在字典中添加双引号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有必要在字典中为键和值添加双引号. 我试图用正则表达式来做,但是我不擅长( 字典可以有两种类型:1)a = {x:2,y:1,z:-3,b:1} 2)a = {x:226/185,y:9/37,z:-409/185,b:133/185} 我们需要找到两种类型的通用解决方案.

It is necessary to add double quotes for the key and value in the dictionary. I tried to do it with regular expressions, but I’m not good at it ( The dictionary can be of two types 1) a = {x: 2, y: 1, z: -3, b: 1} 2) a = {x: 226/185, y: 9/37, z: -409/185, b: 133/185} We need to find a universal solution for both types.

gg={x: 2, y: 1, z: -3, b: 1}
gg1={x: 226/185, y: 9/37, z: -409/185, b: 133/185}


nn="{x: 2, y: 1, z: -3, b: 1}"
nn2="{x: 226/185, y: 9/37, z: -409/185, b: 133/185}"

yy=re.sub(r'(\w*): (\d*)',r'"\1": "\2"',nn)
yy2=re.sub(r'(\w*): (\d*)',r'"\1": "\2"',nn2)
print(yy)
print(yy2)

{"x":"2","y":"1","z":" -3,"b":"1"} {"x":"226"/185,"y":"9"/37,"z":" -409/185,"b":"133"/185}

{"x": "2", "y": "1", "z": ""-3, "b": "1"} {"x": "226"/185, "y": "9"/37, "z": ""-409/185, "b": "133"/185}

推荐答案

import re
nn="{x: 2, y: 1, z: -3, b: 1}"

nn2="{x: 226/185, y: 9/37, z: -409/185, b: 133/185}"
dict_str = lambda data : re.sub(r'(\w+):\s*(-?\d[\d/.]*)',r'"\1": "\2"',data)
for i in [nn,nn2] :
    var1=dict_str(i)
    print(var1)
    # if you want an actual dictionary from var1 you can uncomment the lines  below
    #var2 = var1.replace('{','').replace('}','').replace('"','')
    #var3 ={ j.split(':')[0] : j.split(':')[1] for j in [ k for k in 
        #var1.split(',') ] }
    #print(var3)

这篇关于如何在字典中添加双引号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆