Search code examples
pythondictionarygeneratorpermutationpython-itertools

how to treat dictionary as an "whole thing" when using itertools?


from itertools import product

a = [1, 2, 3]
dict1 = {"x": 1, "y": 2, "z": 3}
dict2 = {"r": 4, "s": 5, "t": 6}

for i in product(a, dict1, dict2):
print(i)

and I got:

(1, 'x', 'r')
(1, 'x', 's')
(1, 'x', 't')
(1, 'y', 'r')
(1, 'y', 's')
(1, 'y', 't')
(1, 'z', 'r')
(1, 'z', 's')
(1, 'z', 't')
(2, 'x', 'r')
(2, 'x', 's')
(2, 'x', 't')
(2, 'y', 'r')
(2, 'y', 's')
(2, 'y', 't')
(2, 'z', 'r')
(2, 'z', 's')
(2, 'z', 't')
(3, 'x', 'r')
(3, 'x', 's')
(3, 'x', 't')
(3, 'y', 'r')
(3, 'y', 's')
(3, 'y', 't')
(3, 'z', 'r')
(3, 'z', 's')
(3, 'z', 't')

But I want to get these instead:

(1, {"x": 1, "y": 2, "z": 3}, {"r": 4, "s": 5, "t": 6})
(2, {"x": 1, "y": 2, "z": 3}, {"r": 4, "s": 5, "t": 6})
(3, {"x": 1, "y": 2, "z": 3}, {"r": 4, "s": 5, "t": 6})

How can I do this? Maybe I should use another function instead of product in this case? Please kindly help. Thanks!


Solution

  • The issues is, that itertools.product will return all product for each element of the iterables provided, so you could get a similar result to your expected result by wraping the two dicts into another iterable:

    for i in list(product(a, [(dict1, dict2)])):
        print(i)
    
    (1, ({'x': 1, 'y': 2, 'z': 3}, {'r': 4, 's': 5, 't': 6}))
    (2, ({'x': 1, 'y': 2, 'z': 3}, {'r': 4, 's': 5, 't': 6}))
    (3, ({'x': 1, 'y': 2, 'z': 3}, {'r': 4, 's': 5, 't': 6}))
    

    The ouput is similar to what you asked for, but the dictionaries are wrappen inside a tupel.