如何附加到多级字典中的列表?

2024-09-30 20:25:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在遍历一个文件,想建立一个多层次的动态字典。最后一级需要存储一个值列表。你知道吗

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。我做错什么了?你知道吗


Tags: and文件keyin列表for字典with
3条回答

这几乎是一个万无一失的方法,确保你不会得到一个错误。按照我们定义myDict的方式,您可以拥有字典“level1”和字典“level2”的任何键。默认情况下,字典树的末尾假定为空列表。你知道吗

myDict = defaultdict(lambda: defaultdict(list))

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)

用以下内容替换for循环下的代码可以解决您的问题:

# if there is no `lvlTwoKey` in `myDict`, initialize a list with `valueFound` in it  
if not myDict[lvlOneKey].get(lvlTwoKey, None):
    myDict[lvlOneKey][lvlTwoKey] = [valueFound]
# otherwise, append to the existing list 
else: 
    myDict[lvlOneKey][lvlTwoKey].append(valueFound)

它使用dictionary上的get()方法,您可以阅读关于here。除此之外,它只是一个标准词典,我发现它通常比复杂的默认词典更具可读性/直观性。你知道吗

如果进一步嵌套,这可能会有点恼人,但使用此模式将起作用。你知道吗

l1keys = [1, 2, 1]
l2keys = ['foo', 'bar', 'spangle']

base = {}
for l1key, l2key in zip(l1keys, l2keys):
    for i in range(5):
        l1 = base.get(l1key, {})
        l2 = l1.get(l2key, [])
        l2.append(i)
        l1[l2key] = l2
        base[l1key] = l1

assert base == {
    1: {'foo': [0, 1, 2, 3, 4], 'spangle': [0, 1, 2, 3, 4]},
    2: {'bar': [0, 1, 2, 3, 4]}
}

相关问题 更多 >