PYTHON如何制作“关联数组”

2024-10-01 22:42:32 发布

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

我编写了一个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>

现在,我只能得到如下的“姓名”和“身份证”:

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

但是我需要所有的子文件夹,在这样一个dict中:

{'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}

Tags: nameclientidconfigxmlfindsubfolderfournisseur
1条回答
网友
1楼 · 发布于 2024-10-01 22:42:32

添加另一个循环

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}

相关问题 更多 >

    热门问题