在嵌套字典中生成所有可能的组合

2024-09-28 23:14:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要测试所有可能的安装配置。配置保存在字典数组中,该数组有时包含嵌套数组。在

下面是配置信息的示例(实际配置要长得多):

config = {'database': 'sqlite',
          'useExisting': False,
          'userCredentials': {'authType': 'windows', 
                              'user': r'.\Testing', 
                              'password': 'testing'
                             }
         }

对于database,选项是['sqlite','mysql','oracle'],对于useExisting,选项是{}。我能弄清楚如何处理所有的排列。在

但是对于userCredentials,选项可能会非常不同。如果authTypedatabase,我需要其他参数。我可以创建一个函数来遍历并创建所有有效的组合,但是如何将它们连接起来呢?或者有更好的方法来生成配置吗?在

userCredentials也可能有不同的设置。例如,我有两个用户帐户,testing1和testing2。我需要用两个用户帐户运行测试,最好是使用所有可能的配置。我很难弄清楚当这样嵌套时,如何递归地生成所有配置。在


Tags: 用户信息configfalse示例sqlite字典windows
1条回答
网友
1楼 · 发布于 2024-09-28 23:14:54

这就是你要找的吗?它构建使用intertools.product列出的数据库、useExisting和authType的所有组合。如果authType是'database',它会用其他参数更新userCredentials。根据需要修改:

from itertools import product

def build_config(db,flag,authType,userPass):
    config = dict(database=db,useExisting=flag)
    config['userCredentials'] = {
        'authType': authType, 
        'user': userPass[0], 
        'password': userPass[1]
    }
    if authType == 'database':
        config['userCredentials'].update(
            dict(extra=1,param=2))
    return config

database = ['sqlite','mysql','oracle']
useExisting = [True, False]
authType = ['windows','database']
userPass = [('testing1','pass1'),('testing2','pass2')]

for options in product(database,useExisting,authType,userPass):
    config = build_config(*options)
    print config

相关问题 更多 >