Splitting a semicolon-separated string to a dictionary, in Python -


i have string looks this:

"name1=value1;name2=value2;name3=value3" 

is there built-in class/function in python take string , construct dictionary, though had done this:

dict = {     "name1": "value1",     "name2": "value2",     "name3": "value3" } 

i have looked through modules available can't seem find matches.


thanks, know how make relevant code myself, since such smallish solutions mine-fields waiting happen (ie. writes: name1='value1=2';) etc. prefer pre-tested function.

i'll myself then.

there's no builtin, can accomplish generator comprehension:

s= "name1=value1;name2=value2;name3=value3" dict(item.split("=") item in s.split(";")) 

[edit] update indicate may need handle quoting. complicate things, depending on exact format looking (what quote chars accepted, escape chars etc). may want @ csv module see if can cover format. here's example: (note api little clunky example, csv designed iterate through sequence of records, hence .next() calls i'm making @ first line. adjust suit needs):

>>> s = "name1='value=2';name2=value2;name3=value3"  >>> dict(csv.reader([item], delimiter='=', quotechar="'").next()           item in csv.reader([s], delimiter=';', quotechar="'").next())  {'name2': 'value2', 'name3': 'value3', 'name1': 'value1=2'} 

depending on exact structure of format, may need write own simple parser however.


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -