Last active
September 26, 2017 07:08
-
-
Save ruxi/079cc200b7f3934d906a0044679abbdf to your computer and use it in GitHub Desktop.
combinations (tuple of dicts) from possible options (dict with lists)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" | |
Author: https://github.com/ruxi | |
Date Created: Tuesday, 26 Sep 2017 | |
last updated: Tuesday, 26 Sep 2017 | |
Python Version: 3.6 | |
""" | |
__author__ = "https://github.com/ruxi" | |
__date_created__ = "Tuesday, 26 Sep 2017" | |
import unittest, itertools | |
def dict_options_to_combinations(adict): | |
"""combinations (tuple of dicts) from possible options (dict with lists) | |
returns: | |
tuple of dict: | |
args: | |
adict (dict of lists) | |
Example | |
input (adict): | |
{ | |
arg1 = ['bob'] | |
arg2 = [True, False] | |
} | |
output: | |
( {arg1:'bob', arg2:True} , arg1:'bob', arg2:False) | |
""" | |
# nested function | |
flatten_list = lambda listoflist: list(itertools.product(*listoflist)) | |
# input validation | |
valid_type = [list] | |
if not all([type(x) in valid_type for x in adict.values()]): | |
typevalues = [type(x) for x in adict.values()] | |
wrongtype = {k:v for k,v in zip(adict.keys(), typevalues) if v not in valid_type} | |
raise Exception(f"list expected but adict had {wrongtype}") | |
# business logic | |
tuple_combintorials = flatten_list(adict.values()) | |
result = [] | |
for combo in tuple_combintorials: | |
datum = {k:v for k,v in zip(adict.keys(), combo)} | |
result.append(datum) | |
return tuple(result) | |
class Test_dict_options_to_combinations(unittest.TestCase): | |
def setUp(self): | |
self.example = dict( | |
data = ["foo", "bar", "baz"] | |
, arg1 = [True, False] | |
) | |
def test_function(self): | |
result = dict_options_to_combinations(self.example) | |
import unittest, sys | |
def run_unittest(MyTest): | |
suite = unittest.TestLoader().loadTestsFromTestCase( MyTest ) | |
return unittest.TextTestRunner(verbosity=1,stream=sys.stderr).run( suite ) | |
run_unittest(Test_dict_options_to_combinations) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment