代码之家  ›  专栏  ›  技术社区  ›  Hooman Bahreini

将xml转换为字典

  •  -1
  • Hooman Bahreini  · 技术社区  · 4 年前

    我有这样一个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
    
    

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

    [故障实例:回溯:<类“TypeError”>:不可损坏的类型: '集合。OrderedDict'

    也在手表窗口,这是我看到的 item :

    enter image description here

    这就是我所看到的 key :

    enter image description here

    1 回复  |  直到 4 年前
        1
  •  1
  •   MohitC    4 年前

    item['job_id'] 是一个dict.你不能在你的 self.job_dict = {} .

    将其更改为 key = item['job_id']['#text'] 相反


    为了更好地理解错误,实现字典键的对象必须实现magic方法 __hash__() . 这意味着密钥必须是可哈希的,才能优化字典结构。

    推荐文章