Skip to content Skip to sidebar Skip to footer

How To Add Double Quotes To The Dictionary?

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 typ

Solution 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)

Post a Comment for "How To Add Double Quotes To The Dictionary?"