【问题标题】:PYTHON How to make "associative array"PYTHON 如何制作“关联数组”
【发布时间】:2018-11-29 14:14:00
【问题描述】:

我制作了一个 python 脚本,需要在 XML 中包含一些参数。所以这里是 XML:

<ROOT>
<FOLDERTYPES>
    <FOLDERTYPE_ID>
        <NAME>FOURNISSEUR</NAME>
        <ID>2</ID>
        <SUBFOLDER>
            <NAME>Administratif</NAME>
            <ID>4</ID>
        </SUBFOLDER>
        <SUBFOLDER>
            <NAME>Commandes</NAME>
            <ID>5</ID>
        </SUBFOLDER>
        <SUBFOLDER>
            <NAME>Factures</NAME>
            <ID>6</ID>
        </SUBFOLDER>
    </FOLDERTYPE_ID>
    <FOLDERTYPE_ID>
        <NAME>CLIENT</NAME>
        <ID>3</ID>
        <SUBFOLDER>
            <NAME>Administratif</NAME>
            <ID>4</ID>
        </SUBFOLDER>
        <SUBFOLDER>
            <NAME>Commandes</NAME>
            <ID>5</ID>
        </SUBFOLDER>
        <SUBFOLDER>
            <NAME>Factures</NAME>
            <ID>6</ID>
        </SUBFOLDER>
        <SUBFOLDER>
            <NAME>Logistique</NAME>
            <ID>7</ID>
        </SUBFOLDER>
    </FOLDERTYPE_ID>
</FOLDERTYPES>

目前,我只能获得如下的“名称”和“ID”:

{'FOURNISSEUR': {'id': '2'}, 'CLIENT': {'id': '3'}}

但我需要在这样的字典中拥有所有子文件夹:

{'FOURNISSEUR': {'id': '2', 'subfolders' : {'Administratif':'4','Commandes':'5','Factures':'6'}}, 'CLIENT': {'id': '3', 'subfolders' : {'Administratif':'4','Commandes':'5','Factures':'6','Logistique':'7'}}

这是我现在拥有的一段代码:

def getFolderTypeArray(fileName):
    result = {}
    with open(fileName, 'rb') as config_file:
        content = config_file.read()
    config = BeautifulSoup(content, "lxml")

    folderTypesId = config.find_all('foldertype_id')
    for folderType in folderTypesId:
        label               = folderType.find('name').string
        folderTypeId        = folderType.find('id').string
        result[label]       = {'id' : folderTypeId}

【问题讨论】:

  • 它们在 python 中被称为字典或dicts,而不是关联数组。你可能需要一个 xml 解析器:docs.python.org/3/library/xml.etree.elementtree.html
  • 好吧,你在哪里制作子文件夹键?
  • @cricket_007 现在我没有为子文件夹编写任何代码。我只是做了一些尝试,但没有成功,因为我不知道如何实现这一点
  • result['subfolders'] = some_dictionary 在循环之后。在循环中构建内部字典...您已经在构建字典。 result[label]{'id' : folderTypeId}

标签: python xml beautifulsoup


【解决方案1】:

在另一个循环中添加

folderTypesId = config.find_all('foldertype_id')
for folderType in folderTypesId:
    label               = folderType.find('name').string
    folderTypeId        = folderType.find('id').string
    subfolders = dict() 
    for s in folderType.find_all('subfolder'):
        subfolders[s.find('name').string] = s.find('id').string
    result[label]       = {'id' : folderTypeId, 'subfolders': subfolders}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-17
    • 2019-01-30
    • 2013-06-14
    • 2011-10-02
    • 1970-01-01
    • 2020-04-24
    • 1970-01-01
    相关资源
    最近更新 更多