-1

So I am trying to format a string to a dict. Meaning, I receive an str input of this sort:

"b:0.1 a:0.5 n:0.2 p:0.1 c:0.1 k:0.1"

And wish to convert it to dict:

{'b':0.1,'a':0.5,'n':0.2 and so on... 'k':0.1}

So far I did the exact opposite:

def string_to_ngram_dict(x):
    y = {"{!s}:{!r}".format(key, val) for (key, val) in x.items()}

input:

{ “b”: 0.1, “a”: 0.4, “n”: 0.2, “p”: 0.1, “c”: 0.1, “k”: 0.1 }

output:

"b:0.1 a:0.5 n:0.2 p:0.1 c:0.1 k:0.1”

So I was wondering if there is any cool trick to reverse this function I wrote. If not, any ideas on how to to do it?

Thanks

Barmar
  • 741,623
  • 53
  • 500
  • 612

4 Answers4

2

Use str.split() and the fact that dict([('k1','v1'), ]) makes a dict properly:

s = "b:0.1 a:0.5 n:0.2 p:0.1 c:0.1 k:0.1"
dict([i.split(':') for i in s.split()])
    
{'b': '0.1', 'a': '0.5', 'n': '0.2', 'p': '0.1', 'c': '0.1', 'k': '0.1'}

you could convert the types later depend on your need. In general type conversion from str is not a good idea as it is unsafe.

Z Li
  • 4,133
  • 1
  • 4
  • 19
  • You can use this for-loop to convert all the values to floats: `for key in test.keys(): test[key] = float(test[key])` – M-Chen-3 Dec 08 '20 at 20:54
  • 1
    @M-Chen-3 or `{k: float(d[k]) for k in d}` where d is the dict output – Z Li Dec 08 '20 at 20:56
1

Use str.split() and dict()

splitStr = 'b:0.1 a:0.5 n:0.2 p:0.1 c:0.1 k:0.1'.split(' ')

strList = []

for s in splitStr :
    strList.append(s.split(':'))
    
dict(strList)
{'b': '0.1', 'a': '0.5', 'n': '0.2', 'p': '0.1', 'c': '0.1', 'k': '0.1'}
Journey R
  • 51
  • 2
0

Using Ryan's convert for type conversion. This will not automatically type all values. It may be fun to play around this, but I do not recommend using it in any serious code (use json instead).

mydict = {}
for i in mystring.split(" "):
    x = i.split(":")
    mydict[x[0]] = convert(x[1])

Ryan's convert is:

def convert(val):
    constructors = [int, float, str]
    for c in constructors:
        try:
            return c(val)
        except ValueError:
            pass
thshea
  • 1,048
  • 6
  • 18
0

Split the string by " " (space)

str.split( )

Then loop through list and populate a dictionary