I want to generate all config from a dict like this:
dict = {
"a": [1,2,3],
"b":{
"b1":[True, False],
"b2":[0],
}
}
List attributes are needed to be enumerated. And output is like this:
config = [{
"a": 1,
"b":{
"b1":True,
"b2":0,
},
{
"a": 2,
"b":{
"b1":True,
"b2":0,
},
...
]
How can I reach this?
I think recursion is a good idea, but I don't know how to use it
CodePudding user response:
There is no value in using recursion for this. A straightforward list comprehension will suffice:
_dict = {
"a": [1, 2, 3],
"b": {
"b1": [True, False],
"b2": [0]
}
}
config = [{'a': k, 'b': {'b1': True, 'b2': 0}} for k in _dict['a']]
print(config)
Output:
[{'a': 1, 'b': {'b1': True, 'b2': 0}}, {'a': 2, 'b': {'b1': True, 'b2': 0}}, {'a': 3, 'b': {'b1': True, 'b2': 0}}]
CodePudding user response:
def merge_dicts(*dict_args):
result = {}
for dictionary in dict_args:
result.update(dictionary)
return result
def dict2combinations(d):
for k, v in d.items():
if isinstance(v, dict):
d[k] = dict2combinations(v)
values = [[{k: i} for i in v] for k, v in d.items()]
return [merge_dicts(*i) for i in product(*values)]
print(dict2combinations(config))
Output:
[{'a': 1, 'b': {'b1': True, 'b2': 0}}, {'a': 1, 'b': {'b1': False, 'b2': 0}}, {'a': 2, 'b': {'b1': True, 'b2': 0}}, {'a': 2, 'b': {'b1': False, 'b2': 0}}, {'a': 3, 'b': {'b1': True, 'b2': 0}}, {'a': 3, 'b': {'b1': False, 'b2': 0}}]