python中2个dict的组合

时间:2014-10-09 08:45:06

标签: python python-2.7 itertools

大家好。我有两个像:

dict_in = {
    'a1': {'b': [1, 2], 'c': [4, 5]}, 
    'a2': {'b': [6, 7], 'c': [8, 10]}
}

我希望输出所有可能不重复的组合,如:

res_dict = [   
   {'a1': {b: 1, c: 4}, 'a2': {'b': 6, 'c': 8}},
   {'a1': {b: 2, c: 4}, 'a2': {'b': 6, 'c': 8}},
   {'a1': {b: 1, c: 5}, 'a2': {'b': 6, 'c':8}},
   {'a1': {b: 1, c: 5}, 'a2': {'b': 6, 'c':8}},
   {'a1': {b: 2, c: 5}, 'a2': {'b': 6, 'c':8}},
   {'a1': {b: 1, c: 4}, 'a2': {'b': 7, 'c':8}},
   {'a1': {b: 1, c: 4}, 'a2': {'b': 7, 'c':10}},
   ....

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

所以,我找到了解决方案:

import itertools as it

dict_comb = {i : itertools.product(*dict_in[i].values()) for i in dict_in.keys()}
keys = dict_comb.keys()
final_dict = itertools.product(* [ dict_comb[key] for key in keys])