使用 python 访问 JSON 文件中的属性并按属性过滤项目

Access attributes in JSON file with python and filter items by attribute

我有一个 json 文件作为输入:

    "Module1": {
      "Description": "",
      "Layer": "1",
      "SourceDir": "path"
      "Attributes": {
      "some",
      },
      "Vendor": "comp"
      },
    "Module2": {
      "Description": "",
      "Layer": "2",
      "SourceDir": "path"
      "Attributes": {
      "some",
      },
      "Vendor": ""
      },
    
    "Module3": {
      "Description": "",
      "Layer": "3",
      "SourceDir": "path"
      "Attributes": {
      "some",
      },
      "Vendor": ""
      },
    
    "Module1": 4
      "Description": "",
      "Layer": "4",
      "SourceDir": "path"
      "Attributes": {
      "some",
      },
      "Vendor": "comp"
      },

如果“Vendor”符合某些条件,我将尝试提取所有模块(它们的名称),在这种情况下,所有带有“Vendor”的模块:“comp”应该与其源目录一起打印(Module1 , 模块 4).

我的代码是:

import json
for k in swc_list.keys():
  if swc_list[k]['Vendor'] == 'comp':
    list_components.append(k)
    sourceDirList.append(swc_list[k]['SourceDir'])

我不断收到错误消息: keyError x

当遍历字典时,使用 .items() 通常更容易 returns 键值对的迭代器,如

for key, value in {}.items():
    pass

您得到的错误 error: keyError x 意味着 x 不在字典中。如果您不确定密钥是否存在,您可以使用 get(key, default) 命令代替,如

x = {}.get('x', 'default')
assert x == 'default'

这是我使用 .items() 遍历字典编辑后的代码。由于输入的数据不清楚,我自由地编辑了它。

data = {
    "Module1": {
        "Description": "",
        "Layer": "1",
        "SourceDir": "path",
        "Attributes": {
            "some",
        },
        "Vendor": "comp",
    },
    "Module2": {
        "Description": "",
        "Layer": "2",
        "SourceDir": "path",
        "Attributes": {
            "some",
        },
        "Vendor": "",
    },
    "Module3": {
        "Description": "",
        "Layer": "3",
        "SourceDir": "path",
        "Attributes": {
            "some",
        },
        "Vendor": "",
    },
    "Module4": {
        "Description": "",
        "Layer": "4",
        "SourceDir": "path",
        "Attributes": {
            "some",
        },
        "Vendor": "comp",
    },
}

和实际代码

list_components = []
sourceDirList = []
combined_list = []

for (key, value) in data.items():
    if value["Vendor"] == "comp":
        source_dir = value['SourceDir']
        list_components.append(key)
        sourceDirList.append(source_dir)

        combined_list.append([key, source_dir])

输出为

>>> print(list_components)
['Module1', 'Module4']

>>> print(sourceDirList)
['path', 'path']

>>> print(combined_list)
[['Module1', 'path'], ['Module4', 'path']]

>>> print(list(zip(list_components, sourceDirList)))
[('Module1', 'path'), ('Module4', 'path')]

编辑:将模块名称和生成的路径合并到元组列表中。