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

时间:2019-08-05 02:03:44

标签: python json dictionary

我尝试访问嵌套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 'title'中提取 ALL points_list.keys()并创建包含密钥(['tosdr/review/stackoverflow.com'] )+提取的'title'值。我该如何构造这样的循环?

2 个答案:

答案 0 :(得分:0)

您必须使用for循环才能从字典和列表中获取所有标题

# 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()}

答案 1 :(得分:0)

您可以尝试以下方法:

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内容。