简体   繁体   English

格式化字符串到 dict

[英]formatting string to dict

So I am trying to format a string to a dict.所以我试图将字符串格式化为字典。 Meaning, I receive an str input of this sort:意思是,我收到这种类型的 str 输入:

"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:并希望将其转换为 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: 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.所以我想知道是否有任何很酷的技巧可以扭转我写的这个 function。 If not, any ideas on how to to do it?如果没有,关于如何做到这一点的任何想法?

Thanks谢谢

Use str.split() and the fact that dict([('k1','v1'), ]) makes a dict properly:使用str.split()dict([('k1','v1'), ])正确地制作dict的事实:

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.一般来说,从str进行类型转换不是一个好主意,因为它是不安全的。

Use str.split() and dict()使用str.split()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'}

Using Ryan 's convert for type conversion.使用Ryanconvert进行类型转换。 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).玩这个可能很有趣,但我不建议在任何严肃的代码中使用它(改用 json)。

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

Ryan's convert is:瑞恩的convert是:

def convert(val):
    constructors = [int, float, str]
    for c in constructors:
        try:
            return c(val)
        except ValueError:
            pass

Split the string by " " (space)用“”(空格)分割字符串

str.split( ) str.split()

Then loop through list and populate a dictionary然后遍历列表并填充字典

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM