修改多级词典

我想创建一个数据结构,用于存储通过平面的各种可能路径,其中多边形散布在平面上。我决定使用嵌套的多级字典来保存在固定点拆分的各种可能路径。


这种字典的一个可能实例是:


path_dictionary = {starting_coordinates:{new_fixpoint1:{new_fixpoint1_1:...}, new_fixpoint2:{new_fixpoint2_1:...}}}

现在我想继续使用来自最后一个固定点的新路径构建该结构,因此我必须在不同的嵌套级别编辑字典。我的计划是提供一个排序的键列表,其中包含给定路径的所有固定点,并且我将有一个函数添加到最后提供的键。


为了实现这一点,我必须能够使用这样的键列表访问字典:


keylist = [starting_coordinates, new_fixpoint1, new_fixpoint1_1, new_fixpoint1_1_3, ...]


path_dictionary = {starting_coordinates:{new_fixpoint1:{new_fixpoint1_1:...}, new_fixpoint2:{new_fixpoint2_1:...}}}


path_dictionary [keylist [0]] [keylist [1]] [keylist [2]] [...] = additional_fixpoint

问题:当我有一定长度的键列表时,如何写入多级字典中的变量嵌套/深度级别?


很感谢任何形式的帮助。


HUX布斯
浏览 115回答 2
2回答

慕田峪7331174

我正在玩弄使用多个索引的想法,以及一个defaultdict. 结果出来了:from collections import defaultdictclass LayeredDict(defaultdict):&nbsp; &nbsp; def __getitem__(self, key):&nbsp; &nbsp; &nbsp; &nbsp; if isinstance(key, (tuple, list)):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if len(key) == 1:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return self[key[0]]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return self[key[0]][key[1:]]&nbsp; &nbsp; &nbsp; &nbsp; return super(LayeredDict, self).__getitem__(key)&nbsp; &nbsp; def __setitem__(self, key, value):&nbsp; &nbsp; &nbsp; &nbsp; if isinstance(key, (tuple, list)):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if len(key) == 1:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self[key[0]] = value&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self[key[0]][key[1:]] = value&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; super(LayeredDict, self).__setitem__(key, value)&nbsp; &nbsp; def __init__(self, *args, **kwargs):&nbsp; &nbsp; &nbsp; &nbsp; super(LayeredDict, self).__init__(*args, **kwargs)&nbsp; &nbsp; &nbsp; &nbsp; self.default_factory = type(self)&nbsp; # override default我还没有完全测试它,但它应该允许你创建任何级别的嵌套字典,并用元组索引它们。>>> x = LayeredDict()>>> x['abc'] = 'blah'>>> x['abc']'blah'>>> x[0, 8, 2] = 1.2345>>> x[0, 8, 1] = 8.9>>> x[0, 8, 'xyz'] = 10.1>>> x[0, 8].keys()[1, 2, 'xyz']>>> x['abc', 1] = 5*** TypeError: 'str' object does not support item assignment不幸的是,不支持扩展符号(或任何它的名称),但您可以将列表或元组作为索引传递。>>> keylist = (0, 8, 2)>>> x[*keylist]*** SyntaxError: invalid syntax (<stdin>, line 1)>>> x[keylist]1.2345此外,isinstance(key, (tuple, list))条件意味着元组不能用作键。

万千封印

您当然可以为这样的嵌套字典编写访问器:def get(d,l):&nbsp; return get(d[l[0]],l[1:]) if l else ddef set(d,l,v):&nbsp; while len(l)>1:&nbsp; &nbsp;d=d[l.pop(0)]&nbsp; l,=l&nbsp; &nbsp;# verify list length of 1&nbsp; d[l]=v(对于长列表,这些都不是有效的;更快的版本将使用变量索引而不是[1:]or pop(0)。)至于其他方法,这里还不足以继续选择一种方法。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python