如何在循环python中使用子字符串制作字典 [英] how to make dictionary using substrings in a loop python
问题描述
我有一个包含数百万个DNA序列的fasta文件-每个DNA序列也都有一个ID.
I have a fasta file with millions of DNA sequences - for each DNA sequence, there is an ID as well.
>seq1
AATCAG #----> 5mers of this line are AATCA and ATCAG
>seq3
AAATTACTACTCTCTA
>seq19
ATTACG #----> 5mers of this line are ATTAC and TTACG
我想做的是,如果DNA序列的长度是6,那么我将使那条线的5聚体(如代码和上面所示).因此,我无法解决的问题是,我想制作一种字典,使字典显示哪个5mers来自哪个 sequence id
.
what I want to do is that if the length of DNA sequence is 6 then I make 5mers of that line (shown in the code and above). So the thing that I have could not solve is that I want to make a dictionary in a way that dictionary shows which 5mers come from which sequence id
.
这是我的代码,但是已经中途了:
here is my code but it is halfway through:
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)
所需的字典应如下所示:
the desired dictionary should look like:
dict = {'seq1':'AATCA', 'seq1':'ATCAG', 'seq19':'ATTAC','seq19':'TTACG'}
推荐答案
using defaultdict
as suggested in Make a dictionary with duplicate keys in Python by @SulemanElahi because You can't have duplicate keys in a dictionary
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
这篇关于如何在循环python中使用子字符串制作字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!