pythonjsonlist

How to create a set of values from multiple list in Python


I have below data in config.json:

{
  "data1": [7, 8],
  "data2": [2015, 2016],
  "data3": [5, 10],
}

It has 3 list with length as 2 but it can have multiple list with n length. I have to read this data and then create a list of list which should have all the values just like set. So output should look like below:

[
    [7, 2015, 5],
    [7, 2015, 10],
    [7, 2016, 5],
    [7, 2016, 10],
    [8, 2015, 5],
    [8, 2015, 10],
    [8, 2016, 5],
    [8, 2016, 10]
]


json_data = open("config.json")
config = json.load(json_data)
json_data.close()

data_list = []
for be in config["data1"]:
    for eof in config["data2"]:
        for bd in config["data3"]:
            data_list.append(bd)

How can I modify the data to have output like above?


Solution

  • Here's some information about a_guest's answer, as you seems to have some trouble understand it.

    json_data = open("config.json")
    config = json.load(json_data)
    json_data.close()
    
    cproduct = list(itertools.product(*config.values()))
    

    product function will give you the cartesian product, that's exactly what you need : all possible combination of elements from different set. We basically use it as product(set_1, set_2, ..., set_n).

    Here, set_1 should be the list stored with the "data1" key, set_2 with "data2" and so on. So you could basically write it.product(config['data1'], config['data2'], config['data3']).

    But how can we deals with new keys in the json without changing our code ?

    To achieve this, guest_a relies on two things :

    So basically, it.product(*config.values()) is equivalent to it.product(config["data1"], ..., config["data_n"]), but is much more flexible.