0

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?

  • 2
    You'll probably need to write your own parser. Here's a decent library for it: http://infohost.nmt.edu/tcc/help/pubs/pyparsing/web/index.html – mVChr May 01 '19 at 22:22
  • Possible duplicate of [Python parsing bracketed blocks](https://stackoverflow.com/questions/1651487/python-parsing-bracketed-blocks) – Iguananaut May 01 '19 at 22:28

1 Answers1

0

If you don't expect it to get much more complicated than what you described, you might be able to get away with some regex. I usually wouldn't recommend it for this purpose, but I want you to be able to start somewhere...

import re
key = input('Enter field and indices (e.g. "fieldA[5][3]"): ')
field = re.match(r'[^[]*', key).group(0)
indices = [int(num) for num in re.findall(r'\[(\d+)]', key)]

This will simply not recognize a missing field or incorrect bracketing and return an empty string or list respectively.

mVChr
  • 49,587
  • 11
  • 107
  • 104