How to generate all combination from values in dict of lists in Python

后端 未结 5 1463
野的像风
野的像风 2020-12-09 03:22

I would like to generate all combinations of values which are in lists indexed in a dict:

{\'A\':[\'D\',\'E\'],\'B\':[\'F\',\'G\',\'H\'],\'C\':[\'I\',\'J\']}         


        
5条回答
  •  醉梦人生
    2020-12-09 03:46

    If you want to keep the key:value in the permutations you can use:

    import itertools
    keys, values = zip(*my_dict.items())
    permutations_dicts = [dict(zip(keys, v)) for v in itertools.product(*values)]
    

    this will provide you a list of dicts with the permutations:

    print(permutations_dicts)
    [{'A':'D', 'B':'F', 'C':'I'}, 
     {'A':'D', 'B':'F', 'C':'J'},
     ...
     ]
    

    disclaimer not exactly what the OP was asking, but google send me here looking for that.

提交回复
热议问题