这个主题并不新鲜,已经在多个帖子中讨论过(链接位于底部)。然而,我觉得资源分散,并不总是清楚什么是最好的方法。我还想引入一些约束来明确定义我期望的行为。
假设我们有一个包含任意数量的项目和任意深度的嵌套字典:
d = {"a": {"b": {"c" : 0}},
"b": {"c" : 1},
"c": 2}
Run Code Online (Sandbox Code Playgroud)
获取其物品的最佳方式是什么?
这种简单的方法相当麻烦,尤其是当有很多嵌套级别时。
>>> d["a"]["b"]["c"]
0
Run Code Online (Sandbox Code Playgroud)
因此,第一个约束是要获取的项的键必须以元组的形式提供,例如:
key = ("a", "b", "c")
Run Code Online (Sandbox Code Playgroud)
现在的目标是创建一些工作原理如下的函数:
>>> getitem(d, key)
0
Run Code Online (Sandbox Code Playgroud)
这种格式也可以方便地直接应用为__getitem__类的方法。
还有一个限制:我希望该函数在被要求获取不存在的密钥时大声失败。
>>> getitem(d, ("asd",))
...
KeyError: 'asd'
Run Code Online (Sandbox Code Playgroud)
这排除了所有使用项目获取来使字典生动的解决方案。
最后,如果可能,请提供低级代码。如果您知道解决此问题的包,请解释底层机制。
参考
我需要从一些大的嵌套字典中获取一些值.出于懒惰,我决定编写一个递归调用自身的函数,直到找到最后一个子元素,或者叶子为空.
由于有字典弹出,每次新调用都有一个新的字典,我想知道它有多高效.
有什么建议?
def recursive_dict_get(item, string, default=False):
if not isinstance(item, dict):
return default
print "called with ", item, "and string", string
if "." in string:
attrs = string.split(".")
parent = attrs.pop(0)
rest = ".".join(attrs)
result = item.get(parent, None)
if result is None:
return default
else:
return recursive_dict_get(item.get(parent, default), rest, default)
else:
return item.get(string, default)
Run Code Online (Sandbox Code Playgroud)
foo = {
"1": {
"2": {
"3": {
"4":{
"5": {
"6": {
"7": "juice"
}
}
}
}
}
}
}
print recursive_dict_get(foo, …Run Code Online (Sandbox Code Playgroud) 我有以下设置:一个函数返回一个具有相同大小(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 函数。
例子: …
我经常发现我有这样的事情:
cur = [0, 0] # the indices into array
matrix = [[1,1,1]]
Run Code Online (Sandbox Code Playgroud)
我在哪里
matrix[cur[0]][cur[1]]
Run Code Online (Sandbox Code Playgroud)
这里有任何类型的解包语法吗?喜欢:
matrix[*cur]
Run Code Online (Sandbox Code Playgroud) 我有这条路可以不时改变:
'#/path/to/key'
Run Code Online (Sandbox Code Playgroud)
路径的各个部分未定义,因此该值也很好
'#/this/is/a/longer/path'
Run Code Online (Sandbox Code Playgroud)
我把这个键分成'/'所以我得到了
['#', 'path', 'to', 'key']
Run Code Online (Sandbox Code Playgroud)
我需要在这条路上找到钥匙,假设我的dict是exp,所以我需要到达这里:
exp['path']['to']['key']
Run Code Online (Sandbox Code Playgroud)
我怎么可能知道如何获得这个键?