matiit
matiit

Reputation: 8017

How to get all possible combinations

I've got something dict like that:

{'Y': [1, 2, 6, 7],
 'X': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24],
 'Z': [0, 3, 6, 9]}

There could be more than 3 variables. I wan't to get all combination of these variables. To get something like:

[{'Y': 1, 'X': 0, 'Z': 0},
 {'Y': 1, 'X': 0, 'Z': 3} ....]

I can't figure algorithm for that. Please help me.

Upvotes: 0

Views: 295

Answers (4)

Kolmar
Kolmar

Reputation: 14224

A bit better looking solution based on the one by Felix Yan:

[dict(zip(your_dict.keys(), item)) for item in itertools.product(*your_dict.values())]

Upvotes: 2

HardlyKnowEm
HardlyKnowEm

Reputation: 3230

The other posters are right: itertools.product is very helpful here. However, some care will be needed to ensure you get the original dictionary keys, because of the way your dictionary is formatted.

import itertools

data = {'Y': [1, 2, 6, 7],
        'X': [0, 1, 2, 3, 4, 5, 6, 7,
              8, 9, 10, 11, 12, 13, 14, 15, 16,
              17, 18, 19, 20, 21, 22, 23, 24],
        'Z': [0, 3, 6, 9]}
# Join the key and value together in tuples
# [[('Y', 1), ('Y', 2), ('Y', 6), ('Y', 7)], ...]
tuples = [[(var, val) for val in data[var]] for var in data]

# Create the dictionary setting values to X, Y, and Z
# [{'Y': 1, 'X': 0, 'Z': 0}, {'Y': 1, 'X': 0, 'Z': 3} ....]
answer = [dict(a) for a in itertools.product(*tuples)]

Upvotes: 4

Felix Yan
Felix Yan

Reputation: 15269

Using list(itertools.product(*your_dict.values())) can simply get it :)

EDIT: for your expected result, I've wrote the following:

 [{key: value[n] for n, key in enumerate(your_dict.keys())} for value in itertools.product(*your_dict.values())]

Not that good-looking but it just works (Only in Python 2.7+).

Upvotes: 2

Alex Reynolds
Alex Reynolds

Reputation: 96974

Use itertools.product().

Upvotes: 1

Related Questions