如何在保留键的同时扩展字典中的字符串列表以生成字典列表?

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

我遇到过几种方法,但 none 似乎适合我正在尝试做的事情。为简单起见,我有一个包含 >20k 键的字典,每个键都有一个字符串列表(不同长度的列表)。我只是想在每个键的列表中获取每个字符串,并在函数在每个单独的字典中进行计算之前生成字典列表。

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

此代码是一个更大函数的一部分,本质上 pep_dict 是一个包含带有字符串列表的键的字典。我在这里得到的输出是一个空列表。

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

预期输出:

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

如有任何见解,我们将不胜感激。

干杯

您可以使用 for 循环简单地遍历嵌套字典。

 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'}]