convert string to dict using list comprehension

后端 未结 8 1887
情歌与酒
情歌与酒 2021-02-05 12:34

I have came across this problem a few times and can\'t seem to figure out a simple solution. Say I have a string

string = \"a=0 b=1 c=3\"

I wan

相关标签:
8条回答
  • 2021-02-05 13:26

    How about a one-liner without list comprehension?

     foo="a=0 b=1 c=3"
     ans=eval( 'dict(%s)'%foo.replace(' ',',')) )
     print ans
    {'a': 0, 'c': 3, 'b': 1}
    
    0 讨论(0)
  • 2021-02-05 13:26

    I like S.Lott's solution, but I came up with another possibility.
    Since you already have a string resembling somehow the way you'd write that, you can just adapt it to python syntax and then eval() it :)

    import re
    string = "a=0 b=1 c=3"
    string2 = "{"+ re.sub('( |^)(?P<id>\w+)=(?P<val>\d+)', ' "\g<id>":\g<val>,', string) +"}"
    dict = eval(string2)
    print type(string), type(string2), type(dict)
    print string, string2, dict
    

    The regex here is pretty raw and won't catch all the possible python identifiers, but I wanted to keep it simple for simplicity's sake. Of course if you have control over how the input string is generated, just generate it according to python syntax and eval it away. BUT of course you should perform additional sanity checks to make sure that no code is injected there!

    0 讨论(0)
提交回复
热议问题