拆分输出以填充嵌套字典 python



我正在尝试填充嵌套字典,但由于我对python(也是Stack Overflow(相当陌生,因此遇到了麻烦。

我有一个带有照片路径的 txt 文件,我想填充从它的拆分到嵌套词典。文本文件的示例如下所示:

/photos/Bob_January_W1_001.png
/photos/Alice_April_W2_003.png

其中 Bob 是用户,一月是月份,W1 是周,001 是照片的 nr

。 等等。

我想在以下结构中填充嵌套词典(基于我所阅读的内容(:

{'Bob': {'January': {'W1': 001, 002, 003}, {'W2': 001, 002,003}}, 'February': {'W3': 001, 002}}  #And so on for other keys as well

到目前为止,我只设法将数字排序为用户,如下所示:

sorteddict = {}
with open('validation_labels.txt','r') as f:
    for line in f:
        split = line.split('_')
        user = split[1]
        month = split[2]
        week = split[3]
        image = split[4]
        if action_class in clipframe:
            sorteddict[user].append(image)
        else:
            sorteddict[user] = [image]

但是现在我想要我描述的嵌套结构。我首先初始化我的嵌套字典,就像这个nesteddict[user][month][week].append(image),但我收到了KeyError: 'Bob'.我也明白,如果陈述和条件,我将需要更多的。但我不知道从哪里开始。

您可以使用嵌套collections.defaultdict集来构建数据:

from collections import defaultdict
dct = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))
with open('validation_labels.txt','r') as f:
    for line in f:
        line = line.strip('/photo/')
        user, month, week, image = line.split('_')
        dct[user][month][week].append(image)

我以前做过这样的事情:

temp = sorteddict
for key in keys[:-1]:
    if key not in temp:
        temp[key] = {}
    temp = temp[key]
temp[keys[-1]] = value

因此,您的密钥需要位于列表(keys列表(中,并且您希望在该密钥链末尾的值处于value

最新更新