首页 > 解决方案 > 使用 for 循环访问 JSON 数据中的特定键/值对

问题描述

我正在尝试从 JSON 数据中的两个特定项目中提取键/值对

数据如下所示:

[{"voc": "UAT",
"concepts":[{"prefLabel":"Solar system",
    "uri":"http://astrothesaurus.org/uat/1528", "score":"15" },
    {"prefLabel":"X-ray astronomy",
    "uri":"http://astrothesaurus.org/uat/1810", "score":"9" },
    {"prefLabel":"Gamma-ray astronomy",
    "uri":"http://astrothesaurus.org/uat/628", "score":"9" }
]}]

我只是尝试使用 for 循环检索 prefLabel 和得分,该循环会将它们保存到一个元组中,以便稍后附加到我当前为空的数据列表中。

这是我当前的循环,但它返回“错误类型”错误:

for concepts in voc_list:
    for prefLabel, score in concepts.items():
        data_tuple = (prefLabel, score)
        data.append(data_tuple)`

任何帮助表示赞赏

标签: pythonjson

解决方案


您可以搜索字典列表,并在匹配所需字符串时附加到data列表中:key

for d in voc_list[0]['concepts']:
    for k, v in d.items():
        if k == 'prefLabel':
            data.append((k, v))

推荐阅读