Anis Souames
Anis Souames

Reputation: 344

How can I create a list of possible combination in a dict?

I have a python dict as following :

test = {"a": value_of_a,"b": value_of_b, "c": value_of_c}

Where value_of_a, value_of_b, value_of_c are all variable which can take 3 values :

I would like to create a list of dicts where each dict contain one combination of these values . for example a dict could be as follow :

test1 = {"a" : 2, "b" : "a", "c" : 45 }
test2 = {"a" : 3, "b" : "a", "c" : 45 }

and so on...

I don't have any Idea how I can proceed to solve this ?

NOTE : These value are only to simplify the task, the original task has more keys and values for each, but If I can do it for those this trivial example I can do it for my original task .

Upvotes: 3

Views: 1002

Answers (3)

Eugene Lisitsky
Eugene Lisitsky

Reputation: 12845

I recommend using special itertools.combinations. Please have a look at examples at the bottom of the page - there're some interesting cases.

>>> import itertools

>>> list(itertools.combinations([1,2,3], 2))
[(1, 2), (1, 3), (2, 3)]

Upvotes: 3

Fomalhaut
Fomalhaut

Reputation: 9745

Enjoy:

import itertools


def iterate_values(S):
    keys, values = zip(*S.items())

    for row in itertools.product(*values):
        yield dict(zip(keys, row))


S = {"a": [1, 2, 3], "b": ["a", "b", "c"], "c": [45, 180, 250]}

for d in iterate_values(S):
    print(d)

Result:

{'a': 1, 'c': 45, 'b': 'a'}
{'a': 1, 'c': 45, 'b': 'b'}
{'a': 1, 'c': 45, 'b': 'c'}
{'a': 1, 'c': 180, 'b': 'a'}
{'a': 1, 'c': 180, 'b': 'b'}
{'a': 1, 'c': 180, 'b': 'c'}
{'a': 1, 'c': 250, 'b': 'a'}
{'a': 1, 'c': 250, 'b': 'b'}
{'a': 1, 'c': 250, 'b': 'c'}
{'a': 2, 'c': 45, 'b': 'a'}
{'a': 2, 'c': 45, 'b': 'b'}
{'a': 2, 'c': 45, 'b': 'c'}
{'a': 2, 'c': 180, 'b': 'a'}
{'a': 2, 'c': 180, 'b': 'b'}
{'a': 2, 'c': 180, 'b': 'c'}
{'a': 2, 'c': 250, 'b': 'a'}
{'a': 2, 'c': 250, 'b': 'b'}
{'a': 2, 'c': 250, 'b': 'c'}
{'a': 3, 'c': 45, 'b': 'a'}
{'a': 3, 'c': 45, 'b': 'b'}
{'a': 3, 'c': 45, 'b': 'c'}
{'a': 3, 'c': 180, 'b': 'a'}
{'a': 3, 'c': 180, 'b': 'b'}
{'a': 3, 'c': 180, 'b': 'c'}
{'a': 3, 'c': 250, 'b': 'a'}
{'a': 3, 'c': 250, 'b': 'b'}
{'a': 3, 'c': 250, 'b': 'c'}

I implemented it as a generator, because it saves your memory. If you need an exact list, you may do this:

lst = list(iterate_values(S))

Upvotes: 5

3novak
3novak

Reputation: 2544

Please specify if you want all possible combinations or randomly selected elements from the value lists. If you want every combination, use @Eugene Litsisky's solution. If you're looking for a set of dictionaries with values randomly drawn from the value lists, you can use numpy.random.choice.

import numpy as np

test1 = {'a': np.random.choice(value_of_a),
         'b': np.random.choice(value_of_b),
         'c': np.random.choice(value_of_c)}

Upvotes: 1

Related Questions