Search code examples
pythondictionarytuplesdefaultdict

Nested looping over tuple values in a dictionary with tuple keys python


I have a defaultdict where the key is a 4-tuple (gene_region, species, ontology, length).

Looping over it is simple:

for gene_region, species, ontology, length in result_dict:

However, I'd like to iterate over it in a nested fashion, like this:

for gene_region
    for species
        for ontology
            ...

How do I do this? Is there no other way than collecting the values first? Or using the following dum-dum way:

for gene_region, _, _, _ in result_dict:
    for _, species, _, _ in result_dict:
        ...

Solution

  • You'd have to collect all the various key elements into lists, then loop over those (using itertools.product(), preferably). The collecting can be done with zip():

    from itertools import product
    
    gene_regions, species_plural, ontologies, lengths = zip(*result_dict)
    
    for gene_region, species, ontology, length in product(gene_regions, species_plural, ontologies, lengths):
        # do something with this combo.
    

    product() produces the same sequence of combinations as if you had nested your loops.