python - 如何访问嵌套 json 文件中的子字典值?
问题描述
我尝试访问嵌套 json 文件中的子字典。如何正确循环这个数据结构?我可以毫无问题地访问高级键,但我无法找到在其中一个键中访问子字典的方法。
我的 JSON 文件如下所示:
with open('all.json') as access_json:
read_content = json.load(access_json)
read_content.keys()
Out[20]: dict_keys(['documents', 'see', 'rated', 'name', 'points', 'slug', 'logo'])
我可以毫无问题地访问
points_list = read_content['points']
type(points_list)
Out[20]: dict
然后,我可以访问单个密钥
points_list['tosdr/review/stackoverflow.com']
这向我展示了
[{'description': 'Generated through the annotate view',
'discussion': 'https://edit.tosdr.org/points/6166',
'id': '6166',
'point': 'bad',
'privacyRelated': True,
'score': 70,
'title': 'This service allows tracking via third-party cookies for purposes including targeted advertising.'},
{'description': 'Generated through the annotate view',
'discussion': 'https://edit.tosdr.org/points/6131',
'id': '6131',
'point': 'bad',
'score': 60,
'title': 'You agree to defend, indemnify, and hold the service harmless in case of a claim related to your use of the service'}]
现在,我可以像这样访问有趣的值
points_list['tosdr/review/stackoverflow.com'][1]['title']
Out[30]: 'You agree to defend, indemnify, and hold the service harmless in case of a claim related to your use of the service'
我想要做的是从 ALL 中提取ALL并创建 包含键 ( ) + 提取值的单独 json 文件。我如何构建这样的循环?'title'
points_list.keys()
['tosdr/review/stackoverflow.com']
'title'
解决方案
您必须使用for
-loop 从字典和列表中获取所有标题
# get elements in dictionary
for key, value in points_list.items():
# get elements in list
for item in value:
print(item['title'])
如果你只想从[1]
result = dict()
for key, value in points_list.items():
result[key] = {'title': value[1]['title']}
或者
result = {key:{'title': value[1]['title']} for key, value in points_list.items()}
推荐阅读
- java - 正则表达式替换文本外部 html标记
- git - 如何在 gitlabci 管道期间知道更新的文件
- android - 安装的 Android PWA 和 Google Play 混合应用版本冲突
- css - Firefox 66 渲染问题:带有矢量效果的 SVG 圆圈:非缩放笔划;
- java - 如何流式传输和收集来自对象集合的实例方法?
- swift - 具有相同名称的 Swift 枚举案例
- filter - 如何封装ansible过滤器?
- javascript - 多约束复杂数据的最佳组合算法
- prometheus - 普罗米修斯每次发出请求时都会使用令牌读取文件吗?
- vue.js - 我将 axios 响应存储到两个不同的“数据”变量中,如果我更改一个变量,它将自动更改另一个变量