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.
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.
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.
Use the str. split() method to split a string on the colons, e.g. my_list = my_str. split(':') .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With