簡體   English   中英

在python中訪問嵌套字典值

[英]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字典中提取beginend的對象。

你也可以這樣做

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM