问题
I am trying to populate a nested dictionary, but are having trouble since I am fairly new to python (also to Stack Overflow).
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
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]
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.
回答1:
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)
回答2:
I have done something like this before:
temp = sorteddict
for key in keys[:-1]:
if key not in temp:
temp[key] = {}
temp = temp[key]
temp[keys[-1]] = value
So, your keys would need to be in a list (the keys
list) and the value that you want at the end of that key chain is in value
来源:https://stackoverflow.com/questions/43234439/split-output-to-populate-nested-dictionary-python