split string on commas but ignore commas with in single quotes and create a dictionary after string split in python
<p>I  have a string as shown below,</p>

<pre><code>someVariable1='9',someVariable2='some , value, comma,present',somevariable5='N/A',someVariable6='some text,comma,= present,'
</code></pre>

<p>I have to split above string on commas but ignore commas within quotes in python and i have to create a dictionary to get the values of variables.</p>

<p>Example:</p>

<pre><code>somedictionary.get('someVariable1')
</code></pre>

<p>I am new to python please help me how can i achieve this in python</p>

<p>Try this regular expression <code>,(?=(?:[^']*\'[^']*\')*[^']*$)</code> for splitting:</p>

<pre><code>import re
re.split(",(?=(?:[^']*\'[^']*\')*[^']*$)",s)

# ["someVariable1='9'",
#  "someVariable2='some , value, comma,present'",
#  "somevariable5='N/A'",
#  "someVariable6='some text,comma,= present,'"]
</code></pre>

<ul>
<li>This uses look ahead syntax <code>(?=...)</code> to find out specific comma to split; </li>
<li>The look up pattern is <code>(?:[^']*\'[^']*\')*[^']*$</code></li>
<li><code>$</code> matches the end of string and optionally matches non <code>'</code> characters <code>[^']*</code></li>
<li>Use non-captured group <code>(?:..)</code> to define a double quote pattern <code>[^']*\'[^']*\'</code> which could appear behind the comma that can acts as a delimiter.</li>
</ul>

<p>This assumes the quotes are always paired.</p>

<p>To convert the above to a dictionary, you can split each sub expression by <code>=</code>:</p>

<pre><code>lst = re.split(",(?=(?:[^']*\'[^']*\')*[^']*$)",s)
dict_ = {k: v for exp in lst for k, v in [re.split("=(?=\')", exp)]}

dict_

# {'someVariable1': "'9'",
#  'someVariable2': "'some , value, comma,present'",
#  'someVariable6': "'some text,comma,= present,'",
#  'somevariable5': "'N/A'"}

dict_.get('someVariable2')
# "'some , value, comma,present'"
</code></pre>

python string python-3.x python-2.x