Creating dictionary from space separated key=value string in Python

后端 未结 2 1983
攒了一身酷
攒了一身酷 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:25

    Try this:

    >>> import re
    >>> dict(re.findall(r'(\S+)=(".*?"|\S+)', s))
    {'key3': '"SrtingWithoutSpace"', 'key2': '"string with space"', 'key1': '1234'}
    

    If you also want to strip the quotes:

    >>> {k:v.strip('"') for k,v in re.findall(r'(\S+)=(".*?"|\S+)', s)}
    

提交回复
热议问题