Reputation: 117
I am trying to add elements in a dictionary keeping key,value pair using python. My input is xml and expected output should be dictionary.
Input:-
<math>
<elements>
<function>
<val>ADD</val>
</function>
<operator>
<val>+</val>
</operator>
<function>
<val>SUB</val>
</function>
<operator>
<val>-</val>
</operator>
</elements>
</math>
I tried parsing and converting it into dictionary but no help. I am using lxml and don't want to use xmltodict.
code till now:-
from lxml import etree
from lxml.etree import _ElementTree, _Element, XMLParser
tree = etree.parsexml('math.xml')
root = tree.getroot()
mathdict = {}
for item in root.findall('./math/elements/function/'):
for d in root.findall('./math/elements/operator/'):
mathdict[item.text] = d.text
It should return dictionary like below:- [ADD:+,SUB:-]
Upvotes: 0
Views: 457
Reputation: 81684
Assuming the order of the XML is always going to be "correct", you can use .iter
and zip
:
import xml.etree.ElementTree as ET
string = '''<math>
<elements>
<function>
<val>ADD</val>
</function>
<operator>
<val>+</val>
</operator>
<function>
<val>SUB</val>
</function>
<operator>
<val>-</val>
</operator>
</elements>
</math>'''
root = ET.fromstring(string)
output = {}
functions, operators = root.iter('function'), root.iter('operator')
for function, operator in zip(functions, operators):
output[function.find('val').text] = operator.find('val').text
print(output)
# {'ADD': '+', 'SUB': '-'}
The dictionary creation and loop can be condensed to a dict comprehension:
output = {function.find('val').text: operator.find('val').text
for function, operator in zip(functions, operators)}
Upvotes: 1