Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Updating dictionary within loops

I have a list of dictionaries in which keys are "group_names" and values are gene_lists.

I want to update each dictionary with a new list of genes by looping through a species_list.

Here is my pseudocode:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

groups=["group1", "group2"]
species_list=["spA", "spB"]
    
def get_genes(group,sp)
    return gene_list

for sp in species_list:
    for group in groups:
        gene_list[group]=get_genes(group,sp)
        gene_list.update(get_genes(group,sp))

The problem with this code is that new genes are replaced/overwritten by the previous ones instead of being added to the dictionary. My question is where should I put the following line. Although, I’m not sure if this is the only problem.

gene_list.update(get_genes(group,sp))

The data I have looks like this dataframe:

data={"group1":["geneA1", "geneA2"],
      "group2":[ "geneB1","geneB2"]}
pd.DataFrame.from_dict(data).T

The data I want to create should look like this:

data={"group1":["geneA1", "geneA2", "geneX"],
      "group2":[ "geneB1","geneB2", "geneX"]}
pd.DataFrame.from_dict(data).T

So in this case, "gene_x" refers to the new genes obtained by the get_genes function for each species and finally updated to the existing dictionary.

Any help would be much appreciated!!

>Solution :

You need to append to the list in the dictionary entry, not assign it.

Use setdefault() to provide a default empty list if the dictionary key doesn’t exist yet.

for sp in species_list:
    for group in groups:
        gene_list.setdefault(group, []).extend(get_genes(group, sp))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading