2017-04-05 97 views
1

我想填充嵌套字典,但有麻烦,因为我相当新的python(也堆栈溢出)。拆分输出来填充嵌套字典python

我有一个包含照片路径的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'。我也明白,如果陈述和条件,我将需要更多。但我不知道从哪里开始。

+0

使用'COLLEC tions.defaultdict'。 – zondo

+0

您可以使用具有默认值的'get()',例如:'nesteddict.get('Bob',{})' –

回答

1

您可以使用嵌套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) 
1

我做了这样的事情之前:

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

所以,你的钥匙就需要在你想在这钥匙链末端的列表(keys列表)和值在value