Last active
January 21, 2019 13:56
-
-
Save grey-area/2a637dc5963354ff2a043dd2c766931c to your computer and use it in GitHub Desktop.
Dictionary list product expansion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from functools import reduce | |
from copy import deepcopy | |
from itertools import product | |
def get_key_paths(d, key_paths=[], param_lists=[], acc=[]): | |
for k, v in d.items(): | |
if isinstance(v, dict): | |
get_key_paths(v, key_paths, param_lists, acc=acc + [k]) | |
elif isinstance(v, list): | |
key_paths.append(acc + [k]) | |
param_lists.append(v) | |
return key_paths, param_lists | |
def set_key_path(d, key_path, v): | |
d1 = reduce(dict.get, key_path[:-1], d) | |
d1[key_path[-1]] = v | |
config = { | |
'L1key1': [0, 1, 2], | |
'L1key2': { | |
'L2key1': 1, | |
'L2key2': [4, 5, 6], | |
} | |
} | |
key_paths, param_lists = get_key_paths(config) | |
param_prod = product(*param_lists) | |
for params in param_prod: | |
config_copy = deepcopy(config) | |
for key_path, param in zip(key_paths, params): | |
set_key_path(config_copy, key_path, param) | |
print(config_copy) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment