Get list of all possible dict configs in Python [d

2019-08-27 07:42发布

问题:

This question already has an answer here:

  • Combine Python Dictionary Permutations into List of Dictionaries 2 answers

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':1, 'b':5},
 {'a':2, 'b':3},
 {'a':2, 'b':4},
 {'a':1, 'b':5}]

I've looked through the docs and SO and it certainly seems to involve itertools.product, but I can't get it without a nested for loop.

回答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}]


回答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}]