【问题标题】:Converting the comma separated values to Python dictionary将逗号分隔值转换为 Python 字典
【发布时间】:2016-11-29 14:24:30
【问题描述】:

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

【问题讨论】:

  • 你能说明你想要得到什么吗?
  • @nick_gabpe - 我需要将输出转换为 Python 字典
  • 那么你的基本问题是如何在python中获取字典以及如何为其添加值?
  • @ jotasi, @ nick_gabpe - 没错,无论如何我需要以字典格式获取“longName”和相应的“版本”,以便进一步处理。
  • 所以我想这实际上是一个重复,在这个answer中得到了很好的回答

标签: python list dictionary ordereddictionary


【解决方案1】:
    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

【讨论】:

    【解决方案2】:

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

    my_dict = {}
    

    然后在循环中给这个字典赋值:

    my_dict[longName] = version
    

    【讨论】:

      【解决方案3】:

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

      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 中,改为使用字典推导式。

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

          猜你喜欢
          • 2021-09-27
          • 2015-05-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-02-11
          • 1970-01-01
          • 2015-07-13
          相关资源
          最近更新 更多