Skip to content Skip to sidebar Skip to footer

How To Split A Python Dictionary For Its Values On Matching A Key

my_dict1 = {'a':1, 'chk':{'b':2, 'c':3}, 'e':{'chk':{'f':5, 'g':6}} } I would like to loop through the dict recursively and if the key is 'chk', split it. Expected output: {'a':1,

Solution 1:

from itertools import product


my_dict = {'a':1, 'chk':{'b':2, 'c':3}, 'e':{'chk':{'f':5, 'g':6}} }


def process(d):
    to_product = []  # [[('a', 1)], [('b', 2), ('c', 3)], ...]
    for k, v in d.items():
        if k == 'chk':
            to_product.append([(k2, v2) 
                              for d2 in process(v) 
                              for k2, v2 in d2.items()])
        elif isinstance(v, dict):
            to_product.append([(k, d2) for d2 in process(v)])
        else:
            to_product.append([(k, v)])
    lst = [dict(l) for l in product(*to_product)]
    unique = []
    [unique.append(item) for item in lst if item not in unique]
    return unique

for i in process(my_dict):
    print(i)

# {'e': {'f': 5}, 'b': 2, 'a': 1}
# {'e': {'g': 6}, 'b': 2, 'a': 1}
# {'e': {'f': 5}, 'a': 1, 'c': 3}
# {'e': {'g': 6}, 'a': 1, 'c': 3}

Post a Comment for "How To Split A Python Dictionary For Its Values On Matching A Key"