Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a string that looks like this:

"Name1=Value1;Name2=Value2;Name3=Value3" 

Is there a built-in class/function in Python that will take that string and construct a dictionary, as though I had done this:

dict = {     "Name1": "Value1",     "Name2": "Value2",     "Name3": "Value3" } 

I have looked through the modules available but can't seem to find anything that matches.


Thanks, I do know how to make the relevant code myself, but since such smallish solutions are usually mine-fields waiting to happen (ie. someone writes: Name1='Value1=2';) etc. then I usually prefer some pre-tested function.

I'll do it myself then.

like image 560
Lasse V. Karlsen Avatar asked Oct 09 '08 11:10

Lasse V. Karlsen


People also ask

How do you split a string separated in Python?

The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

Can you split values in a dictionary Python?

Method 1: Split dictionary keys and values using inbuilt functions. Here, we will use the inbuilt function of Python that is . keys() function in Python, and . values() function in Python to get the keys and values into separate lists.

How do you split a word and colon in Python?

Use the str. split() method to split a string on the colons, e.g. my_list = my_str. split(':') .

How do you split a string into multiple strings in Python?

Split String in Python. To split a String in Python with a delimiter, use split() function. split() function splits the string into substrings and returns them as an array.


1 Answers

There's no builtin, but you can accomplish this fairly simply with a generator comprehension:

s= "Name1=Value1;Name2=Value2;Name3=Value3" dict(item.split("=") for item in s.split(";")) 

[Edit] From your update you indicate you may need to handle quoting. This does complicate things, depending on what the exact format you are looking for is (what quote chars are accepted, what escape chars etc). You may want to look at the csv module to see if it can cover your format. Here's an example: (Note that the API is a little clunky for this example, as CSV is designed to iterate through a sequence of records, hence the .next() calls I'm making to just look at the first line. Adjust to suit your needs):

>>> s = "Name1='Value=2';Name2=Value2;Name3=Value3"  >>> dict(csv.reader([item], delimiter='=', quotechar="'").next()           for item in csv.reader([s], delimiter=';', quotechar="'").next())  {'Name2': 'Value2', 'Name3': 'Value3', 'Name1': 'Value1=2'} 

Depending on the exact structure of your format, you may need to write your own simple parser however.

like image 99
Brian Avatar answered Nov 03 '22 20:11

Brian