Home > Back-end >  Dynamically create nested for loops based on the number of variables
Dynamically create nested for loops based on the number of variables

Time:11-15

I need to execute an expression like the following

 {(i, j, k): config[i][j][k]
  for i in config["content"].keys()
  for j in config["content"][i].keys()
  for k in config["content"][i][j].keys()}

The expression is predicated on the depth on config. Since this has 3 levels we get [i],[j],[k]. If we had 4 levels it would be [i],[j],[k],[l]. So on and so forth.

I would like the resultant expression and dictionary for be generated dynamically. The assumption is that we know the depth and the values for [i],[j],[k] but how do I go about creating the for loops dynamically. Will appreciate any help. Happy to do it in a different way as long as it gives me the resultant dict

CodePudding user response:

You can use a function that recursively flattens sub-dicts and merge the path of keys of the sub-dicts with the key of the current level:

def flatten(config):
    output = {}
    if isinstance(config, dict):
        for key, value in config.items():
            for path, leaf in flatten(value).items():
                output[(key, *path)] = leaf
    else:
        output[()] = config
    return output

Demo: https://replit.com/@blhsing/MustyStripedQuery

  • Related