在python中访问嵌套字典值

2024-09-28 17:06:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python字典的新手,我试图将数字提取为字典值表示中的位置,子类别“span”。字典如下所示:

z = {'denotations': [{'id': ['OMIM:254500', 'MESH:D009101', 'BERN:106985601'],
                  'obj': 'disease',
                  'span': {'begin': 96, 'end': 112}},
                 {'id': ['OMIM:254450', 'MESH:D055728', 'BERN:106922101'],
                  'obj': 'disease',
                  'span': {'begin': 266, 'end': 268}},
                 {'id': ['OMIM:254450', 'MESH:D055728', 'BERN:106922101'],
                  'obj': 'disease',
                  'span': {'begin': 351, 'end': 353}}],
 'logits': {'disease': [[{'end': 112,
                          'id': 'OMIM:254500\tMESH:D009101\tBERN:106985601',
                          'start': 96},
                         0.9999999403953552],
                        [{'end': 268,
                          'id': 'OMIM:254450\tMESH:D055728\tBERN:106922101',
                          'start': 266},
                         0.9999996423721313],
                        [{'end': 353,
                          'id': 'OMIM:254450\tMESH:D055728\tBERN:106922101',
                          'start': 351},
                         0.9999995231628418]]}

我只对外延类感兴趣,更感兴趣的是span中的数字。 我只能设法提取表示信息print(z["denotations"]),我对如何进一步深入字典有点困惑,例如:

是否可以提取跨度信息:

print(z['span'])

Output:
'span': {'begin': 96, 'end': 112}},
'span': {'begin': 266, 'end': 268}},
'span': {'begin': 351, 'end': 353}}]

或者仅仅将数字存储为位置

positions = ([96,112],[266, 268], [351, 353])

Tags: idobj字典数字startendspanbegin
3条回答

诀窍是认识到z['denotations']是一个列表而不是一个字典。因此,您需要遍历此列表中的每个字典以访问所有跨度

positions = []
for item in z['denotations']:
    positions.append([item['span']['begin'], item['span']['end']])
print(positions)

输出

[[96, 112], [266, 268], [351, 353]]

我想你要的是一份理解清单

return [x['span'] for x in z['denotations']]

或对于位置,使用:

return [[x['span']['begin'], x['span']['end']] for x in z['denotations']]

您可以使用列表理解:

>>> [(el["span"]["begin"], el["span"]["end"]) for el in z["denotations"]]
[(96, 112), (266, 268), (351, 353)]

z["denotations"]是一个对象列表,对于每个对象,您都需要从span字典中提取beginend

相关问题 更多 >