Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用for循环从JSON数据访问特定的键/值对_Python_Json - Fatal编程技术网

Python 使用for循环从JSON数据访问特定的键/值对

Python 使用for循环从JSON数据访问特定的键/值对,python,json,Python,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"

我试图从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和score,该循环将它们保存到一个元组中,以便稍后附加到我当前的空数据列表中

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

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

非常感谢您的帮助

您可以搜索词典列表,并在
键与所需字符串匹配时将其附加到
数据
列表中:

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

谢谢你,当我尝试它时,它返回“错误的类型,当预期的数字”。我的值都不是数字,所以我看不到任何解决方案。感谢您的反馈。看起来我无法复制您的JSON数据。这就是我运行它的方式。请随意更改它,以便我可以看到您是如何得到该错误的。