我可以将 defaultdict 或 dict 转换为 Python 中的 ordereddict 吗?

Can I convert a defaultdict or dict to an ordereddict in Python?

我正在尝试解析一个 fasta 文件,然后我想创建另一个文件,它将包含 fasta 文件的所有可能的第 100 个 ATGCN 序列。

例如:

chr1_1-100:ATGC.....GC  
chr1_2-101:ATGC.....GC  
chr1_3-102:ATGC.....GC  
......................  
chr22_1-100:ATGC....cG  
chr22_2-101:ATGC....cG  
......................

我用下面的代码做到了:

    from Bio import SeqIO
    from Bio.Seq import Seq
    from Bio.SeqRecord import SeqRecord
    records = SeqIO.to_dict(SeqIO.parse(open(i1), 'fasta'))
    with open(out, 'w') as f:
       for key in records:
     long_seq_record = records[key]
     long_seq = long_seq_record.seq
     length=len(long_seq)
     alphabet = long_seq.alphabet
     for i in range(0, length-99):  
         short_seq = str(long_seq)[i:i+100]
         text="@"+key+"_"+str(i)+"-"+str(i+100)+":"+"\n"+short_seq+"\n"+"+"+"\n"+"IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII\n"
     f.write(text)

问题是写入的文件不是ordered.means,它可以先包含chr10,然后再包含chr2

问题就在那里,因为解析是使用 dict( 完成的,例如 SeqIO.to_dict(SeqIO.parse(open(i1), 'fasta'))

那么,我可以将 dict 转换为有序 dict 以便我的文件有序吗?或者还有其他方法可以解决吗?

Can I convert a defaultdict or dict to an ordereddict in Python?

是的,您可以转换它 OrderedDict(any_dict) 如果您需要对键进行排序,您可以在创建 OrderedDict 之前对它们进行排序:

>>> from collections import OrderedDict
>>> d = {'c':'c', 'b':'b', 'a':'a'}
>>> o = OrderedDict((key, d[key]) for key in sorted(d))
>>> o.items()[0]
('a', 'a')
>>> o.items()[1]
('b', 'b')
>>> o.items()[2]
('c', 'c')

根本不用费心写任何命令。你不需要 dict 给你的属性,你需要 dict 转换丢失的信息。来自 SeqIO.parse 的记录迭代器已经为您提供了您所需要的:

with open(i1) as infile, open(out, 'w') as f:
    for record in SeqIO.parse(infile, 'fasta'):
        # Do what you were going to do with the record.

如果您需要字典键中的信息,那就是 record.id

您已经正确地确定了问题的原因:to_dict 方法 returns 一个字典,意味着顺序已经丢失。从那时起,就没有办法恢复订单了。

此外,您并没有真正使用字典,因为您按顺序处理所有内容,因此您可以迭代:

for record in SeqIO.parse(open(i1), 'fasta')) :
    key = record.id
    long_seq = record.seq
    ...