拆分输出以填充嵌套字典python [英] Split output to populate nested dictionary python

查看:135
本文介绍了拆分输出以填充嵌套字典python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to populate a nested dictionary, but are having trouble since I am fairly new to python (also to Stack Overflow).

我有一个txt文件带有照片的路径,我想将拆分内容填充到嵌套字典中。文本文件的示例如下所示:

I have a txt file with paths to photos and I would like to populate the splits from it to a nested dictionary. An example of the text file looks like this:

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

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

Where Bob is the user, January is the month, W1 the week and 001 the nr of the photo. Etc.

我想按照以下结构填充嵌套字典(根据我的读物):

I would like to populate a nested dictionary in the following structure (based on what I have read):

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

到目前为止只能对用户进行数字排序,例如:

So far I have only managed to sort the numbers to a user, like this:

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: 鲍勃 。我也了解,如果需要声明和条件,我将需要更多。但我不知道从哪里开始。

But now I want the nested structure I described. I started by initializing my nested dict, like this nesteddict[user][month][week].append(image), but I recieve KeyError: 'Bob'. I also understand that I am going to need a lot more if statements and conditions. But I don't know where to begin.

推荐答案

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

You can use nested sets of collections.defaultdict to build your data:

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)

这篇关于拆分输出以填充嵌套字典python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆