【问题标题】:How to expand a list of strings within dictionary to produce list of dictionaries while retaining key?如何在保留键的同时扩展字典中的字符串列表以生成字典列表?
【发布时间】:2021-06-15 05:00:19
【问题描述】:

我遇到了几种方法,但似乎没有一种适合我正在尝试做的事情。为了简单起见,我有一个包含 >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.]

任何见解将不胜感激。

干杯

【问题讨论】:

  • 也许您应该在每行中做更少的事情,以免让自己感到困惑,并帮助您更好地了解发生了什么。见ericlippert.com/2014/03/05/how-to-debug-small-programs
  • 不是minimal reproducible example 并且缺少数据。 edit 并请修复。
  • 好的,有一个基本的例子。一些键在每个列表中有 100 个字符串。我可以用字符串制作字典列表,但我似乎无法保留键。我不经常使用字典,因此只需对如何使用 dict.items() 解压列表有一个基本的了解。
  • 我已经尝试过一个键值循环,就像我对原始字典所做的那样,但它总是让我的电脑崩溃。
  • stackoverflow.com/questions/58703305/… 这是一个与我想要的类似但似乎不适合我的字典的示例。

标签: python-3.x list dictionary zip key


【解决方案1】:

您可以使用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'}]

【讨论】:

  • 有趣。我之前的一些尝试并不遥远,但我没有考虑使用范围循环来迭代嵌套列表。这是有道理的,尽管我确信有一种更“pythonic”的方式......无论哪种方式,这让我对如何操作字典有了更好的理解。谢谢!
猜你喜欢
  • 1970-01-01
  • 2019-10-05
  • 2012-07-14
  • 2021-01-23
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 2020-06-28
  • 1970-01-01
相关资源
最近更新 更多