How to generate all combination from values in dict of lists in Python

If you want to keep the key:value in the permutations you can use: import itertools keys, values = zip(*my_dict.items()) permutations_dicts = [dict(zip(keys, v)) for v in itertools.product(*values)] this will provide you a list of dicts with the permutations: print(permutations_dicts) [{‘A’:’D’, ‘B’:’F’, ‘C’:’I’}, {‘A’:’D’, ‘B’:’F’, ‘C’:’J’}, … ] Disclaimer: not exactly what the OP was asking, … Read more

Algorithm to select a single, random combination of values?

Robert Floyd invented a sampling algorithm for just such situations. It’s generally superior to shuffling then grabbing the first x elements since it doesn’t require O(y) storage. As originally written it assumes values from 1..N, but it’s trivial to produce 0..N and/or use non-contiguous values by simply treating the values it produces as subscripts into … Read more

Find all combinations of a list of numbers with a given sum

You could use itertools to iterate through every combination of every possible size, and filter out everything that doesn’t sum to 10: import itertools numbers = [1, 2, 3, 7, 7, 9, 10] target = 10 result = [seq for i in range(len(numbers), 0, -1) for seq in itertools.combinations(numbers, i) if sum(seq) == target] print(result) … Read more

Get all possible (2^N) combinations of a list’s elements, of any length

This answer missed one aspect: the OP asked for ALL combinations… not just combinations of length “r”. So you’d either have to loop through all lengths “L”: import itertools stuff = [1, 2, 3] for L in range(len(stuff) + 1): for subset in itertools.combinations(stuff, L): print(subset) Or — if you want to get snazzy (or … Read more