2016-11-29 125 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