python - 使用 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)`
任何帮助表示赞赏
解决方案
您可以搜索字典列表,并在匹配所需字符串时附加到data
列表中:key
for d in voc_list[0]['concepts']:
for k, v in d.items():
if k == 'prefLabel':
data.append((k, v))
推荐阅读
- java - 为什么以及如何编译这个奇怪的方法返回类型?
- android - 使用 Firestore 时避免相同的聊天
- javascript - 如何使 jQuery 构造函数属性全局可见
- asp.net-core - 在不同的服务器上设置 Web.MVC 和主机站点
- cordova - Ionic 应用程序在 android 上运行,但在 iOS 上出现多个插件的 plugin_not_installed 错误
- c# - 如何解决 SharpZipBaseException '标头校验和非法'?
- google-apps-script - 根据谷歌表格信息创建个性化的谷歌表单
- javascript - 这些异步/等待代码之间有区别吗?
- html - 固定表头没有和列对齐
- python - Flake8 抱怨关于内置函数的“未定义变量”