[英]Accessing nested dictionary values in python
我是 Python 字典的新手,我正在尝试将数字提取为字典值表示中的位置,子类别“跨度”。 字典看起来像这样:
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]]}
我只对 denotations 类别感兴趣,对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])
诀窍是要认识到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
字典中提取begin
和end
的对象。
你也可以这样做
from functools import reduce
myList=z['denotations']
# use python reduce
def inside_get(dictionary, *keys):
return reduce(lambda d, key: d.get(key) if d else None, keys, dictionary)
for item in lt:
result= inside_get(item, 'span')
print(result)
Output:
{'begin': 351, 'end': 353}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.