Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Iterate through nested dict, check bool values to get indexes of array

I have a nested dict with boolean values, like:

assignments_dict = {"first": {'0': True,
                              '1': True},
                    "second": {'0': True,
                               '1': False},
                    }

and an array, with a number of elements equal to the number of True values in the assignments_dict:

results_array = [10, 11, 12]

and, finally, a dict for results structured this way:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

results_dict = {"first": {'0': {'output': None},
                          '1': {'output': None}},
                "second": {'0': {'output': None},
                           '1': {'output': None}},
                }

I need to go through the fields in assignment_dict, check if they are True, and if they are take the next element of results_array and substitute it to the corresponding field in results_dict. So, my final output should be:

results_dict = {'first': {'0': {'output': 10},
                          '1': {'output': 11}},
                'second': {'0': {'output': 12},
                           '1': {'output': None}}}

I did it in a very simple way:

# counter used to track position in array_outputs
counter = 0
for outer_key in assignments_dict:
    for inner_key in assignments_dict[outer_key]:
        # check if every field in assignments_dict is True/false
        if assignments_dict[outer_key][inner_key]:
            results_dict[outer_key][inner_key]["output"] = results_array[counter]
            # move on to next element in array_outputs
            counter += 1

but I was wondering if there’s a more pythonic way to solve this.

>Solution :

results_iter = iter(results_array)
for key, value in assignments_dict.items():
    for inner_key, inner_value in value.items():
        if inner_value:
            results_dict[key][inner_key]['output'] = next(results_iter)


print(results_dict)

Output:

{'first': {'0': {'output': 10}, '1': {'output': 11}}, 'second': {'0': {'output': 12}, '1': {'output': None}}}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading