Loop into dictionary of lists and store as list in list

I have a dictionary that I am parsing and essentially, I want to go into all inner values of the dictionary. Then for each interated instance, put these individual values into a list. So that the outer length is 1,

For example, my messy code:

import json
import yaml
from collections import defaultdict
from itertools import zip_longest
logic = yaml.safe_dump('{"$or":[{"$and":[{"baseOperator":null,"operator":"equals","operand1":"metrics.6266","operand2":1},{"baseOperator":null,"operator":"is_true","operand1":"flags.6372","operand2":0}]},{"$and":[{"baseOperator":null,"operator":"equals","operand1":"metrics.6266","operand2":1},{"baseOperator":null,"operator":"is_true","operand1":"flags.15112","operand2":0}]}]}')
logic = yaml.safe_load(logic)
logic = json.loads(logic)
logic = [logic, logic]
operators = defaultdict(list)
for lgl in logic:
    for keys, values in lgl.items():
        for values2 in values:
            for keys2, values3 in values2.items():
                for I,values4 in enumerate(values3):
                    V = []
                    K = []
                    for keys3, values5 in values4.items():
                        if I % len(values3):
                    for kys, vls in zip_longest(V, K):
                        if vls is not None:

Produces the following:

defaultdict(<class 'list'>, {'operator': ['equals', 'is_true', 'equals', 'is_true', 'equals', 'is_true', 'equals', 'is_true'], 'operand1': ['metrics.6266', 'flags.6372', 'metrics.6266', 'flags.15112', 'metrics.6266', 'flags.6372', 'metrics.6266', 'flags.15112'], 'operand2': [1, 0, 1, 0, 1, 0, 1, 0]})

My expected output:

defaultdict(<class 'list'>, {'operator': [[['equals', 'is_true', 'equals', 'is_true'], ['equals', 'is_true', 'equals', 'is_true']]], 'operand1': [[['metrics.6266', 'flags.6372', 'metrics.6266', 'flags.15112'], ['metrics.6266', 'flags.6372', 'metrics.6266', 'flags.15112']]], 'operand2': [[[1, 0, 1, 0], [1, 0, 1, 0]]]})

>Solution :

You need a defaultdict for each outer item, then combine with the outer dict

logics = [logic, logic]
operators = defaultdict(lambda: [[]])
for item in logics:
    inner_operators = defaultdict(list)
    for first_values in item.values():
        for values2 in first_values:
            for second_values in values2.values():
                for values4 in second_values:
                    for keys3, values5 in values4.items():
                        if values5 is not None:

    for key, values in inner_operators.items():

I’ve also changed the key/value iteration to value iteration when key was unused. Also the K V stuff was useless, just use the values in the first loop

Leave a Reply