Python 3.x 创建具有{key:list[]}的dict元素的子集

Python 3.x 创建具有{key:list[]}的dict元素的子集,python-3.x,list,dictionary,data-structures,Python 3.x,List,Dictionary,Data Structures,我有一个dict,每个键都有列表元素。例如 config_dict = {"num":[2,3,4], "dist":[10,30,22], "type":["free"], "uphill":[1e-3, 1e-2, 1e-6] } 我想创建一个函数,为每个键创建所有可能的元素子集,作为一个新的dict new_config = {'congfig_1': { "num":

我有一个dict,每个键都有列表元素。例如

config_dict = {"num":[2,3,4],
               "dist":[10,30,22],
               "type":["free"],
               "uphill":[1e-3, 1e-2, 1e-6]
               }
我想创建一个函数,为每个键创建所有可能的元素子集,作为一个新的dict

new_config = {'congfig_1': { "num":2,
                             "dist":22,
                             "type":"free",
                             "uphill":1e-3
                           }
              'config_2': { "num":3,
                             "dist":22,
                             "type":"free",
                             "uphill":1e-6
                           }
              'config_3': { "num":2,
                             "dist":10,
                             "type":"free",
                             "uphill":1e-3
                           }
               ...
              }
我被困在实现上,因为每个键可能有不同长度的列表。有没有一种优雅的方法可以做到这一点/没有很多循环的pythonic方法

您可以使用:

但是,创建字典列表可能更有意义:

output = [{'num': num, 'dist': dist, 'type': type, 'uphill': uphill}
          for (num, dist, type, uphill) in product(*config_dict.values())]

如果你想写没有库

def combinatrix(dictLeft):
    sol=list()
    key=list(dictLeft.keys())[0]
    temp2=dict(dictLeft)
    del temp2[key]
    if(len(temp2)==0):
        for item in dictLeft.get(key):
            temp=dict()
            temp[key]=item
            sol.append(temp)
    else:
        a=combinatrix(temp2)
        for item in dictLeft.get(key):
            for b in a:
                b=dict(b)
                b[key]=item
                sol.append(b)
    return sol

config_dict = {"num":[2,3,4],
               "dist":[10,30,22],
               "type":["free"],
               "uphill":[1e-3, 1e-2, 1e-6]
               }

sol=combinatrix(config_dict)
print(sol)

添加到@DeepSpace的答案中 我们可以通过

config_keys = config_dict.keys()
for i, values in product(*config_dict.values()):
   output[f'config_{i}'] = dict(zip(config_keys, values))

将输出作为dict列表是否有意义?是的。这也行。我按我想象的方式打字有没有一种方法可以省略显式地写键?我确实让它工作了。但是每次我在dict中添加一个新的键,我必须在这里明确地写出来,我想我们可以做到。我补充了一个答案。将其标记在ans中以备将来参考。
config_keys = config_dict.keys()
for i, values in product(*config_dict.values()):
   output[f'config_{i}'] = dict(zip(config_keys, values))