繁体   English   中英

如何访问嵌套 json 文件中的子字典值?

[英]How do I access sub dictionary values in nested json file?

我尝试访问嵌套 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 points_list.keys()提取所有'title'并创建单独的 json 文件,其中包含密钥 ( ['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()}

你可以试试这个:

def traverse_dicts( obj ) :
    if isinstance( obj, dict) :
        for k in obj :
            if k == 'title' :
                print 'title:', obj[k]
            else :
                traverse_dicts( obj[k] )
    if isinstance( obj, list) :
        for k in obj :
            traverse_dicts( k )

它将递归访问所有级别的所有字典/列表,并在找到时打印title内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM