Get list of all possible dict configs in Python [duplicate]

我们两清 提交于 2019-12-11 20:42:37

问题


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


来源:https://stackoverflow.com/questions/26724860/get-list-of-all-possible-dict-configs-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!