Pyparsing is useful here, especially if you get more complex inputs. See comments in source code below:
from pyparsing import *
EQ = Suppress('=')
key = Word(alphas, alphanums)
value = QuotedString("'", escChar="\\")
parser = OneOrMore(Group(key + EQ + value))
# multiplication with an integer or tuple works too
# parser = 4 * Group(key + EQ + value)
# ONE_OR_MORE = (1,)
# parser = ONE_OR_MORE * Group(key + EQ + value)
sample = r"""
enabled='false' script='var name=\'Bob\'\\n ' index='0' value=''
"""
# parse the sample string
res = parser.parseString(sample)
# pretty-print parsed results
res.pprint()
# convert results to list and make a dict from it
print(dict(res.asList()))
# alternatively, make the parser do the dict-building
parser = Dict(OneOrMore(Group(key + EQ + value)))
res = parser.parseString(sample)
# parsed results look like a list
res.pprint()
# but Dict will define key-values to make a dict-like return object
print(res.dump())
print(res['enabled'])
print(res.keys())
# or access fields using object.attribute notation
print(res.enabled)
prints:
[['enabled', 'false'],
['script', "var name='Bob'\\\n "],
['index', '0'],
['value', '']]
{'index': '0', 'enabled': 'false', 'value': '', 'script': "var name='Bob'\\\n "}
[['enabled', 'false'],
['script', "var name='Bob'\\\n "],
['index', '0'],
['value', '']]
[['enabled', 'false'], ['script', "var name='Bob'\\\n "], ['index', '0'], ['value', '']]
- enabled: false
- index: 0
- script: var name='Bob'\
- value:
false
['index', 'enabled', 'value', 'script']
false