Creating dictionary from space separated key=value string in Python

后端 未结 2 1978
攒了一身酷
攒了一身酷 2020-12-17 15:41

I have string as follows:

s = \'key1=1234 key2=\"string with space\" key3=\"SrtingWithoutSpace\"\'

I want to convert in to a dictionary as

2条回答
  •  臣服心动
    2020-12-17 16:20

    The shlex class makes it easy to write lexical analyzers for simple syntaxes resembling that of the Unix shell. This will often be useful for writing minilanguages, (for example, in run control files for Python applications) or for parsing quoted strings.

    import shlex
    
    s = 'key1=1234 key2="string with space" key3="SrtingWithoutSpace"'
    
    print dict(token.split('=') for token in shlex.split(s))
    

提交回复
热议问题