2016-11-29 114 views
0

我收到XML数据下面使用下面的程序格式转换逗号分隔值Python字典

<?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> 

获取从XML

这给了我下面的"longName""version"输出,我想以字典格式转换以进一步处理

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

预期输出 -

dictionary = {"Plugin Usage - Plugin": "0.3", "Matrix Project Plugin": "4.5"} 
+0

你能澄清你想要得到什么? –

+0

@nick_gabpe - 我需要将我的输出转换为Python字典 –

+0

因此,您的基本问题是如何获得Python中的字典以及如何为其添加值? – jotasi

回答

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 
0

我想你应该创建之初的字典:

my_dict = {} 

然后在循环值分配给这本字典:

my_dict[longName] = version 
0

假设你有所有你的元组存储在列表中,你可以像这样迭代它:

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

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

或者,在Python 3中,改为使用词典理解。

0

其实很简单。首先,你的循环之前初始化字典,然后添加键值对,你让他们:

dictionary = {} 
for plugin in root.findall('plugin'): 
    ... 
    dictionary[longName] = version # In place of the print call