variations = {
'size':{'small':'Small',
'medium':'Medium',
'large':'Large'},
'quantity':{'20l':'20l',
'10l':'10l',
'5l':'5l'},
'color':{'red':'Red',
'blue':'Blue',
'green':'Green'}
}
var_list = [[i,j,k] for i in variations['color'] for j in variations['size'] for k in variations['quantity']]
You can also write the above code as:
var_list = []
for i in variations['color']:
for j in variations['size']:
for k in variations['quantity']:
comb = []
comb.append(i)
comb.append(j)
comb.append(k)
Var_list.append(comb)
Both the var_list outputs:
[['red', 'small', '20l'], ['red', 'small', '10l'], ['red', 'small', '5l'], ['red', 'medium', '20l'], ['red', 'medium', '10l'], ['red', 'medium', '5l'], ['red', 'large', '20l'], ['red', 'large', '10l'], ['red', 'large', '5l'], ['blue', 'small', '20l'], ['blue', 'small', '10l'], ['blue', 'small', '5l'], ['blue', 'medium', '20l'], ['blue', 'medium', '10l'], ['blue', 'medium', '5l'], ['blue', 'large', '20l'], ['blue', 'large', '10l'], ['blue', 'large', '5l'], ['green', 'small', '20l'], ['green', 'small', '10l'], ['green', 'small', '5l'], ['green', 'medium', '20l'], ['green', 'medium', '10l'], ['green', 'medium', '5l'], ['green', 'large', '20l'], ['green', 'large', '10l'], ['green', 'large', '5l']]
var_list contains 3 for loops based on the 3 dictionaries in variations. How to write the above code so that for loops in var_list can be increased or decreased based on the number of dictionaries present in variations?
e.g if 'brand' is also present in variations, a for loop for this 'brand' should be dynamically created in the var_list, so the var_list becomes
var_list = [[i,j,k,l] for i in variations['color'] for j in variations['size'] for k in variations['quantity'] for l in varistions['brands']