Skip to content Skip to sidebar Skip to footer

Split Output To Populate Nested Dictionary Python

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 lik

Solution 1:

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

from collections import defaultdict

dct = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))

withopen('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)

Solution 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

Post a Comment for "Split Output To Populate Nested Dictionary Python"