【问题标题】:how to make dictionary using substrings in a loop python如何在循环python中使用子字符串制作字典
【发布时间】:2021-03-23 09:45:03
【问题描述】:

我有一个包含数百万个 DNA 序列的 fasta 文件 - 每个 DNA 序列都有一个 ID。

>seq1
AATCAG #----> 5mers of this line are AATCA and ATCAG
>seq3
AAATTACTACTCTCTA
>seq19
ATTACG #----> 5mers of this line are ATTAC and TTACG

我想要做的是,如果 DNA 序列的长度为 6,那么我制作该行的 5mers(如代码及以上所示)。所以我无法解决的问题是我想制作一本字典,让字典显示哪些 5mers 来自哪个sequence id

这是我的代码,但已经完成了一半:

from Bio import SeqIO
from Bio.Seq import Seq

with open(file, 'r') as f:
    lst = []
    dict = {}
    for record in SeqIO.parse(f, 'fasta'): #reads the fast file 
        if len(record.seq) == 6:  #considers the DNA sequence length
            for i in range(len(record.seq)):
                kmer = str(record.seq[i:i + 5])
                if len(kmer) == 5:
                    lst.append(kmer)
                    dict[record.id] = kmer  #record.id picks the ids of DNA sequences


    #print(lst)
                    print(dict)

所需的字典应如下所示:

dict = {'seq1':'AATCA', 'seq1':'ATCAG', 'seq19':'ATTAC','seq19':'TTACG'}

【问题讨论】:

  • 字典中不能有重复的键,例如"seq19".
  • 还有其他方法吗?
  • 用列表代替字典
  • 只是提一下 - 如果我有一个列表或字典显示哪个 5mer 来自哪个序列 id - 在下游分析中,我需要遍历每个序列 id 和相关的 5mer

标签: python dictionary sequence biopython


【解决方案1】:

按照@SulemanElahi 在Make a dictionary with duplicate keys in Python 中的建议使用defaultdict ,因为字典中不能有重复的键

from Bio import SeqIO
from collections import defaultdict

file = 'test.faa'

with open(file, 'r') as f:
    dicti = defaultdict(list)
    for record in SeqIO.parse(f, 'fasta'): #reads the fast file 
        if len(record.seq) == 6:  #considers the DNA sequence length
                kmer = str(record.seq[:5])
                kmer2 = str(record.seq[1:])
                dicti[record.id].extend((kmer,kmer2))  #record.id picks the ids of DNA sequences

print(dicti)

for i in dicti:
    for ii in dicti[i]:
        print(i, '   : ', ii) 

输出:

defaultdict(<class 'list'>, {'seq1': ['AATCA', 'ATCAG'], 'seq19': ['ATTAC', 'TTACG']})
seq1    :  AATCA
seq1    :  ATCAG
seq19    :  ATTAC
seq19    :  TTACG

【讨论】:

    猜你喜欢
    • 2017-08-10
    • 2015-04-25
    • 1970-01-01
    • 2023-01-31
    • 2019-03-01
    • 1970-01-01
    • 2017-08-26
    • 2021-02-24
    • 2017-05-10
    相关资源
    最近更新 更多