Python delimited by character only if wrapped in parentheses

I am parsing a large text file that has key value pairs separated by '='. I need to split these key value pairs into a dictionary. I was just going to split into '='. However, I noticed that some of the values ​​contain an equal sign. When a value contains an equal sign, it appears to be always enclosed in parentheses.

Question: How can I split the equal sign only if the equal sign is not between the two parentheses?

Sample data:

PowSup=PS1(type=Emerson,fw=v.03.05.00)

      

Desired output:

{'PowSup': 'PS1(type=Emerson,fw=v.03.05.00)'}

      

UPDATE: The data doesn't seem to have nested parentheses. (Hope this stays in the future)

UPDATE 2: The key should never have an equal sign.

UPDATE 3: The full requirements are much more complex and at this point I am stuck, so I opened a new question here: Python parses the output of a mixed format text file into key signed pair dictionaries

+3


source to share


4 answers


You can try section ('=') to split from first instance



'PowSup=PS1(type=Emerson,fw=v.03.05.00)'.partition('=')[0:3:2]

      

+3


source


mydict=dict()
for line in file:
    k,v=line.split('=',1)
    mydict[k]=v

      



+1


source


Simple solution using function str.index()

:

s = "PowSup=PS1(type=Emerson,fw=v.03.05.00)"
pos = s.index('=')   # detecting the first position of `=` character
print {s[:pos]:s[pos+1:]}

      

Output:

{'PowSup': 'PS1(type=Emerson,fw=v.03.05.00)'}

      

+1


source


You can limit the operation split()

to one split (the first one =

):

>>> x = "PowSup=PS1(type=Emerson,fw=v.03.05.00)"
>>> x.split('=', 1)
['PowSup', 'PS1(type=Emerson,fw=v.03.05.00)']

      

Then you can use these values ​​to populate your dict:

>>> x = "PowSup=PS1(type=Emerson,fw=v.03.05.00)"
>>> key, value = x.split('=', 1)
>>> out = {}
>>> out[key] = value
>>> out
{'PowSup': 'PS1(type=Emerson,fw=v.03.05.00)'}

      

0


source







All Articles