[英]Accessing nested dictionary values in python
I am new to Python dictionaries, i'm trying to extract the numbers as positions inside the dictionary value denotations, sub category 'span'.我是 Python 字典的新手,我正在尝试将数字提取为字典值表示中的位置,子类别“跨度”。 The dictionary looks like this:
字典看起来像这样:
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]]}
I'm only interested in the denotations category, more so the numbers held inside span
.我只对 denotations 类别感兴趣,对
span
中的数字更感兴趣。 I can only manage to extract the denotation information print(z["denotations"])
and I'm a bit stuck on how to go further into the dictionary, example:我只能设法提取外延信息
print(z["denotations"])
并且我有点卡在如何进一步进入字典中,例如:
Is it possible to extract the span information:是否可以提取跨度信息:
print(z['span'])
Output:
'span': {'begin': 96, 'end': 112}},
'span': {'begin': 266, 'end': 268}},
'span': {'begin': 351, 'end': 353}}]
or even store just the numbers as positions?甚至只将数字存储为位置?
positions = ([96,112],[266, 268], [351, 353])
The trick is to recognise that z['denotations']
is a list not a dictionary.诀窍是要认识到
z['denotations']
是一个列表而不是字典。 Therefore, you need to iterate over this list to access each dictionary containing the spans.因此,您需要遍历此列表以访问包含跨度的每个字典。
positions = []
for item in z['denotations']:
positions.append([item['span']['begin'], item['span']['end']])
print(positions)
Output输出
[[96, 112], [266, 268], [351, 353]]
I think what you're looking for is a list comprehension?我认为您正在寻找的是列表理解?
return [x['span'] for x in z['denotations']]
or for the positions, use:或对于职位,使用:
return [[x['span']['begin'], x['span']['end']] for x in z['denotations']]
You can use list comprehension:您可以使用列表理解:
>>> [(el["span"]["begin"], el["span"]["end"]) for el in z["denotations"]]
[(96, 112), (266, 268), (351, 353)]
z["denotations"]
is a list of objects, and for every object you need to extract begin
and end
from the span
dictionary. z["denotations"]
是一个对象列表,对于每个需要从span
字典中提取begin
和end
的对象。
You can also do in this way你也可以这样做
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.