将 xml 转换为字典

Converting an xml to dictionary

我有一个这样的 XML 文件:

<?xml version="1.0" encoding="UTF-8"?>
<items>
  <item type="dict">
    <job_id type="str">id-1</job_id >
    <title type="str">title-1</title>
    <desc type="str">desc-1</desc>
  </item>
  <item type="dict">
    <job_id type="str">id-2</job_id>
    <title type="str">title-2</title>
    <desc type="str">desc-2</desc>
  </item>
</items>

我想将其解析为字典,这样我就可以使用它的 ID 访问作业。所以字典键将是 job_id 并且整个作业定义将是相应的值。

这是我尝试过的:

class Job:
    def __init__(self):
        self.path = "path-to-xml-file"
        self.job_dict = {}

    def load_jobs(self, env, path):
        file = read_from_s3(env, full_path) # reads the job file from S3 bucket
        dict = xmltodict.parse(file)

        for item in dict['items']['item']:
            key = item['job_id']
            self.job_dict[key] = item # <-- I get exception on this line

当我尝试向字典中添加元素时出现以下异常:

[Failure instance: Traceback: <class 'TypeError'>: unhashable type: 'collections.OrderedDict'

同样在手表 window 中,这是我看到的 item:

这就是我看到的 key:

item['job_id'] 是一个命令。您不能将其用作 self.job_dict = {}.

中的密钥

改为key = item['job_id']['#text']


为了更好地理解错误,实现字典键的对象必须实现魔术方法 __hash__()。 这意味着要优化字典结构,键必须是可散列的。