Regular expressions may be a good tool here. It looks like you want to transform elements that look like text1[text2="text3"]
with `text1, {text2: text3}. The regex would look something like this:
(\w+)\[(\w+)=\"(\w+)\"\]
You can modify this expression in any number of ways. For example, you could use something other than \w+
for the names, and insert \s*
to allow optional whitespace wherever you want.
The next thing to keep in mind is that when you do find a match, you need to expand your list. The easiest way to do that would be to just create a new list and append/extend it:
import re
paths = []
pattern = re.compile(r'(\w+)\[(\w+)=\"(\w+)\"\]')
for item in st.split('/'):
match = pattern.fullmatch(item)
if match:
paths.append(match.group(1))
paths.append({match.group(2): match.group(3)})
else:
paths.append(item)
This makes a paths
that is
['data', 'policy', 'line', {'Type': 'BusinessOwners'}, 'risk', 'coverage', {'Type': 'FuelHeldForSale'}, 'id']
[IDEOne Link]
I personally like to split the functionality of my code into pipelines of functions. In this case, I would have the main loop accumulate the paths
list based on a function that returned replacements for the split elements:
def get_replacement(item):
match = pattern.fullmatch(item)
if match:
return match.group(1), {match.group(2): match.group(3)}
return item,
paths = []
for item in st.split('/'):
paths.extend(get_replacement(item))
The comma in return item,
is very important. It makes the return value into a tuple, so you can use extend
on whatever the function returns.
[IDEOne Link]