Home > front end >  Iterate through nested dict, check bool values to get indexes of array
Iterate through nested dict, check bool values to get indexes of array

Time:12-16

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:

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.

CodePudding user response:

Leaving the problem of the order of the dictionaries aside, you can do the following:

it_outputs = iter(array_outputs)
for k, vs in results_dict.items():
    for ki, vi in vs.items():
        vi["output"] = next(it_outputs) if assignments_dict[k][ki] else None


print(results_dict)

Output

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

Note that dictionaries keep insertion order since Python 3.7.

CodePudding user response:

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}}}
  • Related