繁体   English   中英

将列表字典转换为字典字典

[英]Convert dictionary of lists to dictionary of dictionary

当前输出的格式为列表字典

{
    "majestic-service-1.324.02070909": [
        "/home/robotics/arm-services/FeaturesDir.yaml",
        "/home/robotics/arm-service/majestic-service.tar.gz"
    ],
}

我希望将该输出格式更改为如下所示。(字典字典)

{
    "majestic-service-1.324.02070909": {
        "yaml_file": "/home/robotics/arm-services/FeaturesDir.yaml",
        "tar_file": "/home/robotics/arm-services/majestic-service-1.324.02070909.tar.gz",
        "kind": "FeaturesDir"
    }
}

我尝试过的相应代码片段,

 output_dict = {}
 for file in application_files:
    match = re.match(regex_pattern, os.path.basename(file))
    if match:
         if os.path.exists(os.path.join(os.path.dirname(file), "FeaturesDir.yaml")):
              output_dict[file_without_extension(match.string)] = {os.path.join(os.path.dirname(file), "FeaturesDir.yaml")}
              output_dict[file_without_extension(match.string)].append(file)
              output_dict["Kind"] = "FeaturesDir"
         elif os.path.exists(os.path.join(os.path.dirname(file), "output_path/Deviations.yaml")):
                output_dict[file_without_extension(match.string)] = {os.path.join(os.path.dirname(file), "output_path/Deviations")}
                output_dict[file_without_extension(match.string)].append(file)
                output_dict["Kind"] = "Deviations"

# where the function file_without_extension, will return - majestic-service-1.324.02070909 from majestic-service-1.324.02070909.tar.gz

它报告以下错误

AttributeError: 'set' object has no attribute 'append'

我究竟做错了什么 ?

发生错误是因为在这一行output_dict[file_without_extension(match.string)] = {os.path.join(os.path.dirname(file), "output_path/Deviations")}您使用的是 {} 括号,用于 python旨在作为称为 set 的数据类型。 集合没有附加属性,而是添加属性,但它是完全不同的数据类型。 这就是为什么它会向您显示这种错误!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM