我正在遍历一个文件,想建立一个多层次的动态字典。最后一级需要存储一个值列表。你知道吗
myDict = defaultdict(dict)
for key in lvlOneKeys: # this I know ahead of time so I set up my dictionary with first level. I'm not sure if this is necessary.
myDict[key] = {}
with open(myFile, "rb") as fh:
for line in fh:
# found something, which will match lvlOneKey and dynamically determine lvlTwoKey and valueFound
# ...
myDict[lvlOneKey][lvlTwoKey].append(valueFound)
我需要这样做,因为lvlTwoKey将被发现多次不同的valueFound的
不幸的是,这段代码导致了lvlOneKey的KeyError。我做错什么了?你知道吗
这几乎是一个万无一失的方法,确保你不会得到一个错误。按照我们定义
myDict
的方式,您可以拥有字典“level1”和字典“level2”的任何键。默认情况下,字典树的末尾假定为空列表。你知道吗用以下内容替换
for
循环下的代码可以解决您的问题:它使用dictionary上的
get()
方法,您可以阅读关于here。除此之外,它只是一个标准词典,我发现它通常比复杂的默认词典更具可读性/直观性。你知道吗如果进一步嵌套,这可能会有点恼人,但使用此模式将起作用。你知道吗
相关问题 更多 >
编程相关推荐