通过变量访问嵌套字典

Mat*_*ieu 2 python dictionary

我有以下设置:一个函数返回一个具有相同大小(100k 点)的 N 个时间线的字典。字典返回看起来像:

timelines = dict()
timelines["Name1"] = dict()
timelines["Name1"]["Name2"] = dict()
timelines["Name1"]["Name3"] = dict()
timelines["Name1"]["Name2"]["a"] = # List of 100k points
timelines["Name1"]["Name2"]["b"] = # List of 100k points
timelines["Name1"]["Name2"]["c"] = # List of 100k points
timelines["Name1"]["Name3"]["b"] = # List of 100k points
timelines["Name1"]["Name2"]["c"] = # List of 100k points
timelines["Name1"]["a"] = # List of 100k points
timelines["Name1"]["b"] = # List of 100k points
timelines["Name2"] # and so on.
Run Code Online (Sandbox Code Playgroud)

您可能已经理解,时间线(点列表)并不总是存储在同一级别中。有时我可以用 1 个键访问它,有时用 2 个,有时用 5 个。这些键会给我情节的标签,是必要的。我的计划是将一个键元组传递给 plot 函数。

例子:

T = ("Name1", "Name2", "b") 
# Will allow me to access the timeline:
timelines["Name1"]["Name2"]["b"]
# by doing:
timelines[T[0]][T[1]][T[2]]
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,我自己编写了字典路径 ( [T[0]][T[1]][T[2]]),但是如何使用未知大小的元组 T 访问正确的时间线?如何将元组解包到字典路径中?

谢谢 :)

aws*_*ice 6

我实际上会这样做,这很可能是最快的方法

from functools import reduce
from operator import getitem

path = ['Name1', 'Name2', 'a']

reduce(getitem, path, dictionary)
Run Code Online (Sandbox Code Playgroud)

Lambda调用可能会变得昂贵,尤其是随着数据的增长,更不用说getitem会比这里列出的任何其他方法都快,因为它纯粹是在C