Simple way to convert a string to a dictionary

后端 未结 10 2388
我在风中等你
我在风中等你 2020-12-11 17:36

What is the simplest way to convert a string of keyword=values to a dictionary, for example the following string:

name=\"John Smith\", age=34, height=173.2,          


        
10条回答
  •  死守一世寂寞
    2020-12-11 18:24

    I think you just need to set maxsplit=1, for instance the following should work.

    string = 'name="John Smith", age=34, height=173.2, location="US", avatar=":, =)"'
    newDict = dict(map( lambda(z): z.split("=",1), string.split(", ") ))
    

    Edit (see comment):

    I didn't notice that ", " was a value under avatar, the best approach would be to escape ", " wherever you are generating data. Even better would be something like JSON ;). However, as an alternative to regexp, you could try using shlex, which I think produces cleaner looking code.

    import shlex
    
    string = 'name="John Smith", age=34, height=173.2, location="US", avatar=":, =)"'
    lex = shlex.shlex ( string ) 
    lex.whitespace += "," # Default whitespace doesn't include commas
    lex.wordchars += "."  # Word char should include . to catch decimal 
    words = [ x for x in iter( lex.get_token, '' ) ]
    newDict = dict ( zip( words[0::3], words[2::3]) )
    

提交回复
热议问题