PYTHON如何制作;关联数组";

PYTHON如何制作;关联数组";,python,xml,beautifulsoup,Python,Xml,Beautifulsoup,我制作了一个python脚本,需要在XML中包含一些参数。下面是XML: <ROOT> <FOLDERTYPES> <FOLDERTYPE_ID> <NAME>FOURNISSEUR</NAME> <ID>2</ID> <SUBFOLDER> <NAME>Administratif</NAME>

我制作了一个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', '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}
加入另一个循环

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}

它们在python中称为字典或dict,而不是关联数组。您可能需要一个xml解析器:那么,您在哪里生成子文件夹键?@cricket_007现在我没有为子文件夹编写任何代码。我只是做了一些尝试,但没有成功,因为我不知道如何实现这个检查:
result['subfolders']=some_dictionary
。在循环中构建内部字典。。。你已经在编字典了<代码>结果[标签]和
{'id':folderTypeId}
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}