Jai
Jai

Reputation: 177

Converting result set to a dict with pyparsing

I'm trying to convert the result set of parsing to a dict with pyparsing. But dictionary contains only the last member of result set, not all of them. What am i missing?

Here's my code:

from pyparsing import *

test = """
pci24 u2480-L0
fcs1 g4045-L1
pci25 h6045-L0
en192 v7024-L3
pci26 h6045-L1
"""

grammar_pci = Combine("pci" + Word( nums )).setResultsName("name") + Word( alphanums + "-" ).setResultsName("loc")
grammar_non_pci = Suppress( Regex( r"(?!pci).*" ) )

grammar = OneOrMore( Group(grammar_pci).setResultsName("pci_slots") | grammar_non_pci, stopOn=StringEnd())

def main():
  data = grammar.parse_string(test, parseAll=True)
  print(data)
  data_dict = data.as_dict()
  print(data_dict)

if __name__ == "__main__":
    main()

And the outputs of data and data_dict:

[['pci24', 'u2480-L0'], ['pci25', 'h6045-L0'], ['pci26', 'h6045-L1']]
{'pci_slots': {'name': 'pci26', 'loc': 'h6045-L1'}}

pyparsing version: 3.0.9

Upvotes: 2

Views: 157

Answers (1)

Muhammad Ali
Muhammad Ali

Reputation: 489

I hope, this will fix the issue (set listAllMatches=True in setResultName of 'pci_slots')

from pyparsing import *

test = """
pci24 u2480-L0
fcs1 g4045-L1
pci25 h6045-L0
en192 v7024-L3
pci26 h6045-L1
"""

grammar_pci = Combine("pci" + Word( nums )).setResultsName("name") + Word( alphanums + "-" ).setResultsName("loc")
grammar_non_pci = Suppress( Regex( r"(?!pci).*" ) )

grammar = OneOrMore( Group(grammar_pci).setResultsName("pci_slots", listAllMatches=True) | grammar_non_pci, stopOn=StringEnd())


data = grammar.parse_string(test, parseAll=True)
print(data)
data_dict = data.as_dict()
print(data_dict)

Upvotes: 2

Related Questions