dictionary - Get list of all possible dict configs in Python -
dictionary - Get list of all possible dict configs in Python -
this question has reply here:
combine python dictionary permutations list of dictionaries 2 answersi have dict describes possible config values, e.g.
{'a':[1,2], 'b':[3,4,5]}
i want generate list of acceptable configs, e.g.
[{'a':1, 'b':3}, {'a':1, 'b':4}, {'a':1, 'b':5}, {'a':2, 'b':3}, {'a':2, 'b':4}, {'a':1, 'b':5}]
i've looked through docs , , seems involve itertools.product
, can't without nested loop.
you don't need nested for
loop here:
from itertools import product [dict(zip(d.keys(), combo)) combo in product(*d.values())]
product(*d.values())
produces required value combinations, , dict(zip(d.keys(), combo))
recombines each combination keys again.
demo:
>>> 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)) 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}] >>> 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}]
python dictionary itertools
Comments
Post a Comment