简体   繁体   English

遍历嵌套字典,检查 bool 值以获取数组索引

[英]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:和一个数组,其中元素的数量等于 assignments_dict 中 True 值的数量:

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.我需要遍历 assignment_dict 中的字段,检查它们是否为真,以及它们是否为 results_array 的下一个元素并将其替换为 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.但我想知道是否有更多的 pythonic 方法来解决这个问题。

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.请注意,自 Python 3.7 以来,字典保持插入顺序。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM