Reputation: 19
I have a dictionary which has value as a list.
thisdict = { 'G1' : [10,20],
'G2' : [12,13]
}
I want to create new dictionary with all possible 4 combinations.
C1 :[10,12]
C2 :[10,13]
C3 :[20,12]
C4 :[20,13]
How do I create that ?
Upvotes: 0
Views: 95
Reputation: 2004
As other stated, you can use itertools.product
for this.
But you have just two lists, you can also just use two for
loops:
> d = { f'C{i+1}': {'G1':g1e, 'G2':g2e}
for i, (g1e, g2e) in
enumerate((g1e, g2e) for g1e in thisdict['G1']
for g2e in thisdict['G2']) }
> d
{'C1': {'G1': 10, 'G2': 12},
'C2': {'G1': 10, 'G2': 13},
'C3': {'G1': 20, 'G2': 12},
'C4': {'G1': 20, 'G2': 13}}
NB: I used the format requested in the comment to another answer.
Upvotes: 0
Reputation: 5012
Is this acceptable?
from itertools import product
d = {}
offset = 1
for e in product(thisdict['G1'], thisdict['G2']):
d[f'C{offset}'] = list(e)
offset += 1
print(d)
Output:
{'C1': [10, 12], 'C2': [10, 13], 'C3': [20, 12], 'C4': [20, 13]}
Upvotes: 1
Reputation: 204
I think you are looking for: itertools.combinations()
This might help too Getting all combinations of key/value pairs in Python dict
Upvotes: 2