Can't get pyparsing Dict() to return nested dictionary

假如想象 提交于 2019-11-30 18:17:44

Two problems:

  • You are missing a pp.Dict around pp.delimitedList to make asDict on the inner result work correctly
  • You are only calling asDict on the outermost ParsingResult instance, leaving the inner ParsingResult "uninterpreted"

I tried the following:

from pyparsing import *
field_name = field_val = Word(alphanums)
colon = Suppress(Literal(':'))

expr = Dict(Group(
    field_name +
    nestedExpr(content =
        Dict(delimitedList( 
            Group(field_name + colon + field_value), 
            delim = ';' 
        ))
    )
))

Then used it like this:

>>> res = expr.parseString('foo(bar:baz;x:y)')
>>> type(res['foo'])
<class 'pyparsing.ParseResults'>
>>> { k:v.asDict() for k,v in res.asDict().items() }
{'foo': {'x': 'y', 'bar': 'baz'}}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!