1
votes

How can I use itertools to simplify this nested for loop?

def get_test_cases():

    with open("file_path", "r", encoding="utf-8") as index_file:
        data = yaml.safe_load(index_file)

    for a_dict in data:
        for a_name, b_list in a_dict.items():
            for b_dict in b_list:
                for b_name, c_list in b_dict.items():
                    for c_dict in c_list:
                        for c_name, d_list in c_dict.items():
                            for d_case in d_list:
                                yield a_name, b_name, c_name, d_case
Can you add sample data and corresponding output?trincot
I don't think there's anything in itertools that helps you deal with such a deeply nested data structure. You might be able to write your own recursive function that iterates through arbitrarily nested lists and dicts, but if this is the only situation you need to do this in, it wouldn't necessarily be clearer than what you already have. If the data file is under your control, you might want to redesign it with a less nested format.Blckknght
You should provide a sample of data as user @trincot suggests and explain what you're trying to do here - if you're selecting this data from a data structure that contains a lot of other data, there may be no straightforward way to do this, but if you share a sample, people may have some useful suggestions.Grismar
Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.Community