I would like to create a dictionary from an XML file unsing xpath. Here’s an example of the XML:
JavaScript
x
12
12
1
</Contract>
2
<Contract ID="1">
3
<UnwantedPatterns>
4
<Pattern>0</Pattern>
5
<Pattern>1</Pattern>
6
</Contract>
7
<Contract ID="2
8
<UnwantedPatterns>
9
<Pattern>0</Pattern>
10
<Pattern>1</Pattern>
11
</Contract>
12
What I would like it’s having the contract ID as key and the unwanted patterns as value. Here’s my code:
JavaScript
1
9
1
UnwantedPatterns = []
2
key = []
3
DictUP = {}
4
5
for ID in root.xpath('//Contracts'):
6
key = ID.xpath('./Contract/@ID')
7
for patterns in root.xpath('.//Contract/UnwantedPatterns/Pattern'):
8
DictUP[key] = UnwantedPatterns.append(patterns.text)
9
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
JavaScript
1
2
1
key = ID.xpath('./Contract/@ID')
2
try
JavaScript
1
2
1
key = ID.xpath('./Contract/@ID')[0]
2
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
JavaScript
1
7
1
for ID in root.xpath('//Contracts'):
2
key = ID.xpath('./Contract/@ID')[0]
3
_patterns = []
4
for unwanted in root.xpath('.//Contract/UnwantedPatterns'):
5
_patterns.extend([pattern.text for pattern in unwanted.xpath('./Pattern')])
6
DictUP[key] = _patterns
7