pyparsing produces different results for asDict() and asList()

72 Views Asked by At

I have no ideas why pyparsing produces different results for asDict() and asList(). Please push me in the right direction.

import pyparsing as pp


WALRUS = pp.Keyword(':=').suppress()
number = pp.pyparsing_common.number
hex_number = pp.Literal('16#').suppress() + pp.Word(pp.hexnums+'_')
YesNo = pp.CaselessKeyword('YES').setParseAction(lambda t: True)\
        | pp.CaselessKeyword('NO').setParseAction(lambda t: False)
       
dblQuoString = pp.dblQuotedString().addParseAction(pp.removeQuotes)

propertyName = pp.Word(pp.alphas)('key') # + pp.Keyword(':=').suppress()
# value = dblQuoString | YesNo | hex_number | number | pp.Word(pp.alphanums + '.')  # the same result
value = pp.MatchFirst([dblQuoString,
                      YesNo,
                      hex_number,
                      number,
                      pp.Word(pp.alphanums + '.')]
                      )
value.setDebug()

key_value = propertyName + WALRUS + value('value')


if __name__ == "__main__":
    test_string = r"""Description := "Anything" """
    r = key_value.parseString(test_string)
    print(r.asDict())
    print(r.asList())

...and

{'key': 'Description', 'value': ['Anything']}
['Description', 'Anything']

Why 'Anything' is wrapped to list when result asDict?

I'm expected {'key': 'Description', 'value': 'Anything'}

1

There are 1 best solutions below

0
DamirX On

Okay, this is some kind of magic of pyparsing, the reasons for which are not entirely clear to me.

value = dblQuoString gives the output 'value': 'Anything'

value = dblQuoString ^ YesNo ^ hex_number ^ number ^ pp.Word(pp.alphanums + '.') outputs a list 'value': ['Anything']

I decided for myself this way:

value.addParseAction(lambda t: t[0])