首页 > 解决方案 > 如何访问嵌套 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'

标签: pythonjsondictionary

解决方案


您必须使用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()}

推荐阅读