Home > Net >  Create a dictionary with variable number of keys and variable number of for loops
Create a dictionary with variable number of keys and variable number of for loops

Time:07-05

I have already written code in this way:

base_points = [ {'cHW':value1, 'cHWtil':value2} for value1 in [-1.5, -.8]  for value2 in [-1.5, -.8]]

The output is just a list of dictionaries:

[{'cHW': -1.5, 'cHWtil': -1.5},
 {'cHW': -1.5, 'cHWtil': -0.8},
 {'cHW': -0.8, 'cHWtil': -1.5},
 {'cHW': -0.8, 'cHWtil': -0.8}]

But what I want to do now is have a number of keys as variable. This means I also need a variable number of for loops. I thought of solving this recursively. I can implement the variable number for loop like that in a simple way. But I am not sure how to implement the varying number of keys.

I hope someone can help me.

CodePudding user response:

This will do what I believe your question is asking:

keys = ['key1', 'key2', 'key3']
values = [-1.5, -.8]
from itertools import product
base_points = [{keys[i]:combo[i] for i in range(len(keys))} for combo in product(values, repeat=len(keys))]

Output:

[{'key1': -1.5, 'key2': -1.5, 'key3': -1.5},
 {'key1': -1.5, 'key2': -1.5, 'key3': -0.8},
 {'key1': -1.5, 'key2': -0.8, 'key3': -1.5},
 {'key1': -1.5, 'key2': -0.8, 'key3': -0.8},
 {'key1': -0.8, 'key2': -1.5, 'key3': -1.5},
 {'key1': -0.8, 'key2': -1.5, 'key3': -0.8},
 {'key1': -0.8, 'key2': -0.8, 'key3': -1.5},
 {'key1': -0.8, 'key2': -0.8, 'key3': -0.8}]

Explanation:

  • The variables keys and values are lists of arbitrary length
  • itertools.product() provides nested for-loop behavior to cycle through the items in values at each key position so that a separate dictionary can be created for each possible combination of values at each key position
  • Related