Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating dictionary from space separated key=value string in Python

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?

like image 577
Hemant Shah Avatar asked Jan 21 '11 22:01

Hemant Shah


1 Answers

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))
like image 125
Jochen Ritzel Avatar answered Oct 06 '22 23:10

Jochen Ritzel