14
votes

I have string as follows:

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

I want to convert in to a dictionary as follows:

key  | value
-----|--------  
key1 | 1234
key2 | string with space
key3 | SrtingWithoutSpace

How do I do this in Python?

2
What should happen if your string is 'key1=""foo"bar key2="baz'? - Mark Byers
I am parsing output of a log file and I do not expect output in any other format. - Hemant Shah

2 Answers

19
votes

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)}
29
votes

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))