通过变量访问嵌套字典

时间:2019-02-14 12:22:31

标签: python dictionary

我有以下设置:函数返回一个字典,其中N个时间轴的大小相等(100k点)。字典返回的样子:

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.

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

示例:

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

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

谢谢:)

4 个答案:

答案 0 :(得分:4)

我实际上会这样做,这将是最快的方法

from functools import reduce
from operator import getitem

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

reduce(getitem, path, dictionary)

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

中实现的

答案 1 :(得分:2)

您可以使用reduce

from functools import reduce

timelines = dict()
timelines["Name1"] = dict()
timelines["Name1"]["Name2"] = dict()
timelines["Name1"]["Name2"]["b"] = 'my data'

T = ("Name1", "Name2", "b") 

data = reduce(lambda d, key: d[key], T, timelines)

print(data)
# my data

初始值是您的timeline字典。在T元组上进行reduce迭代,并在每次迭代时调用lambda函数。 lambda有两个参数:第一个是累加值,在这种情况下为当前字典d,第二个是在迭代过程中从元组获取的键。 Lambda返回d[key],它成为下一次迭代的新累加值。

答案 2 :(得分:1)

您可以使用递归方法

def access_my_dict(my_dict, tuple_keys):
    value = my_dict[tuple_keys[0]]
    if isinstance(value, dict):
        return access_my_dict(value, tuple_keys[0:])
    return value

答案 3 :(得分:1)

像这样遍历数据结构:

timelines = dict()
timelines["Name1"] = dict()
timelines["Name2"] = dict()
timelines["Name1"]["Name2"] = dict()
timelines["Name1"]["Name3"] = dict()
timelines["Name1"]["Name2"]["a"] = []  # List of 100k points
timelines["Name1"]["Name2"]["b"] = [12, 67, 45]  # List of 100k points
timelines["Name1"]["Name2"]["c"] = [12, 45]  # 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"]["Name23"] = dict()
timelines["Name2"]["Name23"]["Z"] = []  # and so on.


def get_time_line(path):
    data = timelines
    for path_element in path:
        data = data[path_element]
    return data

path = ("Name1", "Name2", "b")
print(get_time_line(path))

输出:

[12, 67, 45]