'How to iterate through all dictionary combinations
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
Solution 1:[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}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
