简体   繁体   中英

Dynamically create nested for loops based on the number of variables

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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