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
source to share
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)'}
source to share