thejahcoop
thejahcoop

Reputation: 170

How to expand a list of strings within dictionary to produce list of dictionaries while retaining key?

I have come across several approaches but none seem to fit what I am trying to do. To keep it simple, I have a dictionary with >20k keys and each key has a list of strings (lists of different lengths). I am simply trying to take each string within the list of each key and generate of the list of dictionaries before the function does calculations within each individual dictionary.

pep_dic={gene1:[str1,str2,str3], gene2:[str1,str2], etc.}

This code is part of a bigger function, essentially pep_dict is a dictionary that contains a key with a list of strings. The output I am getting here is an empty list.

raw=df[[target, identifier]].set_index(identifier).to_dict()[target]
pep_dict = {}
pep_dic_list = []
for gene,peptide in raw.items():
    pep_dict[gene] = list(parser.cleave(peptide,rule=rule,min_length=min_length,exception=exception,missed_cleavages=missed))
pep_dic_list = [dict(zip(pep_dict.keys(), i)) for i in zip(*pep_dict.values())]
return pep_dic_list

expected output:

pep_dict_list=[{gene1:str1},{gene1:str2},...{gene2:str1},etc.]

Any insight would be greatly appreciated.

Cheers

Upvotes: 0

Views: 534

Answers (1)

Rima
Rima

Reputation: 1455

You can simple loop through nested dictionary using for loop.

 pep_dic={'gene1':['str1','str2','str3'], 'gene2':['str1','str2']}
    pep_dic_list = []
    
    for k, lst in pep_dic.items():    
        d = {}
        for i in range(len(lst)):
            d.update({k: lst[i]})
            new_d = d.copy()
            pep_dic_list.append(new_d)
    
    
    print(pep_dic_list)

#[{'gene1': 'str1'}, {'gene1': 'str2'}, {'gene1': 'str3'}, {'gene2': 'str1'}, {'gene2': 'str2'}]

Upvotes: 1

Related Questions