【问题标题】:How to add double quotes to the dictionary?如何在字典中添加双引号?
【发布时间】:2019-04-01 10:04:02
【问题描述】:

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

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}

【问题讨论】:

  • 试试r'(\w*):\s*(-?\d[\d/.]*)'正则表达式
  • 看起来像 XY 问题。我猜你想创建一个 JSON。是这样吗?字典的来源也是 - 即第二种“类型”的 dict 具有小数值(例如 226/185)
  • 如果你想创建 json,试试import json; json.dumps(your_dict) 应该可以处理它

标签: python regex python-3.x formatting


【解决方案1】:
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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-19
    相关资源
    最近更新 更多