How to iterate through all dictionary combinations
Asked Answered
B

2

5

Consider I have the following dictionary:

someDict = {
  'A': [1,2,3],
  'B': [4,5,6],
  'C': [7,8,9]
}

Is there an easy way I can iterate through to create new dictionaries in a loop for all of the possible combinations, ie?

{'A' : 1, 'B': 4, 'C':7}
{'A' : 1, 'B': 4, 'C':8}
{'A' : 1, 'B': 4, 'C':9}
{'A' : 2, 'B': 4, 'C':7}

etc

Bequeath answered 2/11, 2020 at 11:51 Comment(0)
S
7

You could use itertools.product as follows:

from itertools import product

someDict = {
    'A': [1, 2, 3],
    'B': [4, 5, 6],
    'C': [7, 8, 9]
}

keys, values = zip(*someDict.items())
result = [dict(zip(keys, p)) for p in product(*values)]

for d in result:
    print(d)

Output

{'A': 1, 'B': 4, 'C': 7}
{'A': 1, 'B': 4, 'C': 8}
{'A': 1, 'B': 4, 'C': 9}
{'A': 1, 'B': 5, 'C': 7}
{'A': 1, 'B': 5, 'C': 8}
{'A': 1, 'B': 5, 'C': 9}
{'A': 1, 'B': 6, 'C': 7}
{'A': 1, 'B': 6, 'C': 8}
{'A': 1, 'B': 6, 'C': 9}
{'A': 2, 'B': 4, 'C': 7}
{'A': 2, 'B': 4, 'C': 8}
{'A': 2, 'B': 4, 'C': 9}
{'A': 2, 'B': 5, 'C': 7}
{'A': 2, 'B': 5, 'C': 8}
{'A': 2, 'B': 5, 'C': 9}
{'A': 2, 'B': 6, 'C': 7}
{'A': 2, 'B': 6, 'C': 8}
{'A': 2, 'B': 6, 'C': 9}
{'A': 3, 'B': 4, 'C': 7}
{'A': 3, 'B': 4, 'C': 8}
{'A': 3, 'B': 4, 'C': 9}
{'A': 3, 'B': 5, 'C': 7}
{'A': 3, 'B': 5, 'C': 8}
{'A': 3, 'B': 5, 'C': 9}
{'A': 3, 'B': 6, 'C': 7}
{'A': 3, 'B': 6, 'C': 8}
{'A': 3, 'B': 6, 'C': 9}
Surbeck answered 2/11, 2020 at 11:56 Comment(0)
B
1

Another approach with product:

p = product(*[product(k, v) for k, v in someDict.items()])

for i in p:
    print(dict(i))

Output:

{'A': 1, 'B': 4, 'C': 7}
{'A': 1, 'B': 4, 'C': 8}
{'A': 1, 'B': 4, 'C': 9}
{'A': 1, 'B': 5, 'C': 7}
{'A': 1, 'B': 5, 'C': 8}
{'A': 1, 'B': 5, 'C': 9}
{'A': 1, 'B': 6, 'C': 7}
{'A': 1, 'B': 6, 'C': 8}
{'A': 1, 'B': 6, 'C': 9}
{'A': 2, 'B': 4, 'C': 7}
{'A': 2, 'B': 4, 'C': 8}
{'A': 2, 'B': 4, 'C': 9}
{'A': 2, 'B': 5, 'C': 7}
{'A': 2, 'B': 5, 'C': 8}
{'A': 2, 'B': 5, 'C': 9}
{'A': 2, 'B': 6, 'C': 7}
{'A': 2, 'B': 6, 'C': 8}
{'A': 2, 'B': 6, 'C': 9}
{'A': 3, 'B': 4, 'C': 7}
{'A': 3, 'B': 4, 'C': 8}
{'A': 3, 'B': 4, 'C': 9}
{'A': 3, 'B': 5, 'C': 7}
{'A': 3, 'B': 5, 'C': 8}
{'A': 3, 'B': 5, 'C': 9}
{'A': 3, 'B': 6, 'C': 7}
{'A': 3, 'B': 6, 'C': 8}
{'A': 3, 'B': 6, 'C': 9}
Boren answered 2/11, 2020 at 12:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.