将逗号分隔值转换为Python字典

时间:2016-11-29 14:24:31

标签: python list dictionary ordereddictionary

我以下面的格式获取XML数据

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

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

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

预期产出 -

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

4 个答案:

答案 0 :(得分:0)

我认为你应该在开头创建一个字典:

my_dict = {}

然后在循环中为该字典赋值:

my_dict[longName] = version

答案 1 :(得分: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中,改为使用dict理解。

答案 2 :(得分:0)

实际上,它非常简单。首先,在循环之前初始化字典,然后在获取键值对时添加它们:

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

答案 3 :(得分: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