0

I am getting the XML data in below format

<?xml version="1.0"?>
<localPluginManager>
    <plugin>
        <longName>Plugin Usage - Plugin</longName>
        <pinned>false</pinned>
        <shortName>plugin-usage-plugin</shortName>
        <version>0.3</version>
    </plugin>
    <plugin>
        <longName>Matrix Project Plugin</longName>
        <pinned>false</pinned>
        <shortName>matrix-project</shortName>
        <version>4.5</version>
    </plugin>
</localPluginManager>

Used below program to fetch the "longName" and "version" from the XML

import xml.etree.ElementTree as ET
import requests
import sys
response = requests.get(<url1>,stream=True)
response.raw.decode_content = True
tree = ET.parse(response.raw)
root = tree.getroot()
for plugin in root.findall('plugin'):
    longName = plugin.find('longName').text
    shortName = plugin.find('shortName').text
    version = plugin.find('version').text
    master01 = longName, version
    print (master01,version)

Which gives me below output which I want to convert in dictionary format to process further

('Plugin Usage - Plugin', '0.3')
('Matrix Project Plugin', '4.5')

Expected Output -

dictionary = {"Plugin Usage - Plugin": "0.3", "Matrix Project Plugin": "4.5"}
Darshan Deshmukh
  • 327
  • 1
  • 3
  • 15

4 Answers4

0

I think you should create a dictionary at the beginning:

my_dict = {}

then assign values to this dictionary in the loop:

my_dict[longName] = version
yohann.martineau
  • 1,403
  • 1
  • 16
  • 22
0

Assuming you have all your tuples stored in a list, you can iterate over it like this:

tuple_list = [('Plugin Usage - Plugin', '0.3'), ('Matrix Project Plugin', '4.5')]
dictionary = {}

for item in tuple_list:
    dictionary[item[0]] = item[1]

Or, in Python 3, a dict comprehension instead.

Nils Gudat
  • 11,046
  • 3
  • 33
  • 51
0

It's very simple, actually. First, you initialize the dictionary before the loop, then you add key-value pairs as you get them:

dictionary = {}
for plugin in root.findall('plugin'):
    ...
    dictionary[longName] = version # In place of the print call
zondo
  • 19,040
  • 7
  • 42
  • 82
0
    import xml.etree.ElementTree as ET
    import requests
    import sys
    response = requests.get(<url1>,stream=True)
    response.raw.decode_content = True
    tree = ET.parse(response.raw)
    root = tree.getroot()
    mydict = {}
    for plugin in root.findall('plugin'):
        longName = plugin.find('longName').text
        shortName = plugin.find('shortName').text
        version = plugin.find('version').text
        master01 = longName, version
        print (master01,version)
        mydict[longName]=version
nick_gabpe
  • 4,093
  • 5
  • 28
  • 36