Home > Software engineering >  How to nest a dictionary in another empty dictionary inside a nested for loop?
How to nest a dictionary in another empty dictionary inside a nested for loop?

Time:12-03

I created two for loops where the loop for roi in rois is nested in the loop for subject in subjects. My aim is creating a dictionary called dict_subjects that includes yet another dictionary that, in turn, includes the key-value pair roi: comp.

This is my current code:

rois = ["roi_x", "roi_y", "roi_z" ...] # a long list of rois

subjects = ["Subject1", "Subject2", "Subject3", "Subject4", "Subject5" ... ] # a long list of subjects

dict_subjects = {}
for subject in subjects:
    for roi in rois:
        data = np.loadtxt(f"/volumes/..../xyz.txt") # Loads data
        comp = ... # A computation with a numerical result
        
        dict_subjects[subject] = {roi:comp}

My current coding issue is that the nested for loop creates the dictionary dict_subjects that, paradigmatically for the first two subjects, looks like this:

{'Subject1': {'roi_z': -1.1508099817085136}, 'Subject2': {'roi_z': -0.5746447574557193}}

Hence, the nested for loops only add the last roi from the list of rois. I understand that the problem is a constant overwriting of the last roi by the line dict_subjects[subject] = {roi:comp}.

When changing this line of code to dict_subjects[subject] = [{roi:ple[0]}], I get the following key error KeyError: 'Subject1' since the dictionary dict_subjects is empty.

Question: How is it possible to start with an empty dictionary, namely dict_subjects, yet adding the nested hierarchy of subjects and rois: comp to it?

CodePudding user response:

To fix your code, you need to create the inner dictionary for each subject before you start the loop for roi in rois. You can do this by adding the following code before the loop

for roi in rois:

dict_subjects[subject] = {}

This will create an empty dictionary for each subject in the outer loop, and you can then add key-value pairs to that dictionary inside the inner loop. Your code should now look something like this:

rois = ["roi_x", "roi_y", "roi_z" ...]  # a long list of rois
subjects = ["Subject1", "Subject2", "Subject3", "Subject4", "Subject5" ...]  # a long list of subjects

dict_subjects = {}

for subject in subjects:
    dict_subjects[subject] = {}

    for roi in rois:
        data = np.loadtxt(f"/volumes/..../xyz.txt")  # Loads data
        comp = ...  # A computation with a numerical result

        dict_subjects[subject][roi] = comp

This should create the dictionary you want, with a nested dictionary for each subject containing the key-value pairs of roi: comp for each roi in rois.

  • Related