Skip to content Skip to sidebar Skip to footer

Get List Of All Possible Dict Configs In Python

I have dict that describes possible config values, e.g. {'a':[1,2], 'b':[3,4,5]} I want to generate list of all acceptable configs, e.g. [{'a':1, 'b':3}, {'a':1, 'b':4}, {'a'

Solution 1:

You don't need a nested for loop here:

from itertools import product
[dict(zip(d.keys(), combo)) for combo in product(*d.values())]

product(*d.values()) produces your required value combinations, and dict(zip(d.keys(), combo)) recombines each combination with the keys again.

Demo:

>>> from itertools import product
>>> d = {'a':[1,2], 'b':[3,4,5]} 
>>> list(product(*d.values()))
[(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)]
>>> [dict(zip(d.keys(), combo)) for combo in product(*d.values())]
[{'a': 1, 'b': 3}, {'a': 1, 'b': 4}, {'a': 1, 'b': 5}, {'a': 2, 'b': 3}, {'a': 2, 'b': 4}, {'a': 2, 'b': 5}]
>>> from pprint import pprint
>>> pprint(_)
[{'a': 1, 'b': 3},
 {'a': 1, 'b': 4},
 {'a': 1, 'b': 5},
 {'a': 2, 'b': 3},
 {'a': 2, 'b': 4},
 {'a': 2, 'b': 5}]

Solution 2:

You can also try this:

>>> dt={'a':[1,2], 'b':[3,4,5]} 
>>> [{'a':i,'b':j} for i in dt['a'] for j in dt['b']]
[{'a': 1, 'b': 3}, {'a': 1, 'b': 4}, {'a': 1, 'b': 5}, {'a': 2, 'b': 3}, {'a': 2, 'b': 4}, {'a': 2, 'b': 5}]

Post a Comment for "Get List Of All Possible Dict Configs In Python"