生成大型字典的排列组合子字典并用于测试的技术需求
Solution to Generate All Sub-Dictionary Combinations and Run Tests
Got it, let's break down how to solve this problem exactly as you need it: we have a main dictionary where each key maps to a list of options (each option is a list like [a]). We need to generate every possible sub-dictionary that picks exactly one option per key, then pass each sub-dictionary to test_program() for testing.
Step-by-Step Implementation (Python)
The perfect tool for this is itertools.product, which generates the Cartesian product of all your option lists—this gives us every possible combination of one option from each key's list. Here's a complete, reusable implementation:
import itertools def run_all_tests(main_dictionary): # Extract keys and their corresponding option lists (preserves order in Python 3.7+) keys = list(main_dictionary.keys()) option_groups = list(main_dictionary.values()) # Generate every possible combination of options (one per key) for option_combo in itertools.product(*option_groups): # Pair keys with their selected option to create the sub-dictionary sub_dict = dict(zip(keys, option_combo)) # Pass the sub-dictionary to your test function test_program(sub_dict) # Example test function (replace this with your actual test logic) def test_program(sub_dict): print(f"Running test with sub-dictionary: {sub_dict}") # Example main dictionary (adjust this to your actual data) main_dictionary = { 1: [[10], [20], [30]], 2: [[40], [50]], 3: [[60]] } # Execute all tests run_all_tests(main_dictionary)
How This Works
- Extract Keys & Options: We first get the list of keys and their corresponding option lists from your main dictionary. In Python 3.7+, regular dictionaries preserve insertion order, so the keys will stay in the order you defined them.
- Generate Combinations:
itertools.product(*option_groups)takes each list of options and generates every possible combination of picking one element from each list. For the example above, this would create 3 * 2 * 1 = 6 total combinations. - Build Sub-Dictionaries: For each combination, we use
dict(zip(keys, option_combo))to pair each key with its selected option, creating the sub-dictionary format you need. - Run Tests: Each sub-dictionary is immediately passed to
test_program()for testing.
Notes for Edge Cases
- If you're using a Python version older than 3.7, dictionaries don't preserve order. To fix this, use
collections.OrderedDictfor yourmain_dictionaryto ensure keys stay in your desired order. - This solution works no matter how many keys your main dictionary has, or how many options each key maps to—it scales automatically.
内容的提问来源于stack exchange,提问作者Nicholas Kellas
相关产品推荐
相关产品推荐

