sreekanth ramagiri sreekanth ramagiri - 11 months ago 56
Python Question

split string on commas but ignore commas with in single quotes and create a dictionary after string split in python

I have a string as shown below,

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

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.



I am new to python please help me how can i achieve this in python

Answer Source

Try this regular expression ,(?=(?:[^']*\'[^']*\')*[^']*$) for splitting:

import re

# ["someVariable1='9'",
#  "someVariable2='some , value, comma,present'",
#  "somevariable5='N/A'",
#  "someVariable6='some text,comma,= present,'"]
  • This uses look ahead syntax (?=...) to find out specific comma to split;
  • The look up pattern is (?:[^']*\'[^']*\')*[^']*$
  • $ matches the end of string and optionally matches non ' characters [^']*
  • Use non-captured group (?:..) to define a double quote pattern [^']*\'[^']*\' which could appear behind the comma that can acts as a delimiter.

This assumes the quotes are always paired.

To convert the above to a dictionary, you can split each sub expression by =:

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


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

# "'some , value, comma,present'"