Skip to content
Advertisement

Create a dictionary from an XML using xpath

I would like to create a dictionary from an XML file unsing xpath. Here’s an example of the XML:

</Contract>
    <Contract ID="1">
      <UnwantedPatterns>
        <Pattern>0</Pattern>
        <Pattern>1</Pattern>
 </Contract>
    <Contract ID="2
      <UnwantedPatterns>
        <Pattern>0</Pattern>
        <Pattern>1</Pattern>
 </Contract>

What I would like it’s having the contract ID as key and the unwanted patterns as value. Here’s my code:

UnwantedPatterns = []
key = []
DictUP = {}

for ID in root.xpath('//Contracts'):
    key = ID.xpath('./Contract/@ID')
    for patterns in root.xpath('.//Contract/UnwantedPatterns/Pattern'):
        DictUP[key] = UnwantedPatterns.append(patterns.text)

I get the error “unhashable type: ‘list'”. Thank you for your help, the output should look like that:

{1: 0,1

2: 0,1}

Advertisement

Answer

xpath returns list, so instead of

key = ID.xpath('./Contract/@ID')

try

key = ID.xpath('./Contract/@ID')[0]

As for output, as dictionary cannot have multiple values with the same key DictUP[key] = UnwantedPatterns.append(patterns.text) will overwrite value on each iteration.

Try

for ID in root.xpath('//Contracts'):
    key = ID.xpath('./Contract/@ID')[0]
    _patterns = []
    for unwanted in root.xpath('.//Contract/UnwantedPatterns'):
        _patterns.extend([pattern.text for pattern in unwanted.xpath('./Pattern')])
    DictUP[key] = _patterns
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement