Generating all possible combinations in a nested dictionary

时光怂恿深爱的人放手 提交于 2019-12-08 02:10:07

问题


I need to test all possible installation configurations possible. The configurations are kept in a dictionary array that sometimes contains nested arrays.

Here's a sample of the configuration information (actual configuration is much longer):

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

For database, options are ['sqlite','mysql','oracle'], and for useExisting, the options are [True, False]. I can figure out how to go through all permutations of those.

But for userCredentials, the options can be quite different. If authType is database, I need additional parameters. I can create a function that'll loop through and create all valid combinations, but how do I join them? Or is there a better way to generate the configurations?

The userCredentials may also have different settings. For instance, I have two user accounts, testing1 and testing2. I'll need to run the tests with both user accounts, and preferably with all possible configurations. I'm having trouble figuring out how to recursively generate all configurations when it's nested like this.


回答1:


Is this what you are looking for? It builds all combinations of database, useExisting, and authType listed using intertools.product. If authType is 'database' it updates the userCredentials with additional parameters. Modify as needed:

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


来源:https://stackoverflow.com/questions/12178291/generating-all-possible-combinations-in-a-nested-dictionary

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