-2

I have this string 'id,obj1,"string, etc",obj2', now I need to split this into an dict like this:

{
  1 = 'id',
  2 = 'obj1',
  3 = 'string, etc',
  4 = 'obj2'
}

I have been playing around with regular expressions, trying to divide the string but with no success. Any help is appreciated

leko
  • 2,308
  • 1
  • 11
  • 11

2 Answers2

9

Something like the following may work for your use case:

>>> s = 'id,obj1,"string, etc",obj2'
>>> import csv
>>> dict(enumerate(next(csv.reader([s])),start=1))
{1: 'id', 2: 'obj1', 3: 'string, etc', 4: 'obj2'}
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
0

You could apply a regular expression like /([^"]*)(?:"([^"]*)")?/ repeatedly to the input. On each match, the first subgroup match contains any elements that can be split by commas directly, and the second subgroup match (if there is one) contains a quoted entry.

DSimon
  • 3,280
  • 2
  • 21
  • 24