I'm trying to parse user input that specifies a value to look up in a dictionary.
For example, this user input may be the string fieldA[5]
. I need to then look up the key fieldA
in my dictionary (which would be a list) and then grab the element at position 5
. This should be generalizable to any depth of lists, e.g. fieldA[5][2][1][8]
, and properly fail for invalid inputs fieldA[5[
or fieldA[5][7
.
I have investigated doing:
import re
key = "fieldA[5]"
re.split('\[|\]', key)
which results in:
['fieldA', '5', '']
This works as an output (I can lookup in the dictionary with it), but does not actually enforce or check pairing of brackets, and is unintuitive in how it reads and how this output would be used to look up in the dictionary.
Is there a parser library, or alternative approach available?