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

2024-05-02 09:15:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在获取以下格式的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"}

Tags: textimportprojectversionresponse格式usagexml
3条回答
    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

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

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

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

或者,在python3中,使用dict理解。你知道吗

我认为你应该在一开始就编一本字典:

my_dict = {}

然后在循环中将值赋给此字典:

my_dict[longName] = version

相关问题 更多 >