Python에서 defaultdict 또는 dict를 Ordereddict로 변환할 수 있습니까? (Can I convert a defaultdict or dict to an ordereddict in Python?)


문제 설명

Python에서 defaultdict 또는 dict를 Ordereddict로 변환할 수 있습니까? (Can I convert a defaultdict or dict to an ordereddict in Python?)

fasta 파일을 구문 분석하려고 하고 fasta 파일의 ATGCN의 가능한 모든 100번째 시퀀스를 포함하는 다른 파일을 만들고 싶습니다.

예:

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)

문제는 작성된 파일이 순서가 없다는 것입니다. 즉, chr10을 먼저 포함한 다음 chr2를 포함할 수 있습니다. .

파싱이 dict( 예를 들어, SeqIO.to_dict(SeqIO.parse(open(i1), 'fasta')).

내 파일이 정렬되도록 사전을 정렬된 사전으로 변환할 수 있습니까? 아니면 솔루션을 얻을 수 있는 다른 방법이 있습니까?


참조 솔루션

방법 1:

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

Yes, you can convert it OrderedDict(any_dict) and if you need to order the keys, you can sort them before creating the 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')

방법 2:

Don't bother making any sort of dict at all. You don't need the properties a dict gives you, and you need the information the dict conversion loses. The record iterator from SeqIO.parse already gives you what you need:

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.

If you need the information that was in the dict key, that's record.id.

방법 3:

You have correctly identified the cause of the problem: the to_dict method returns a dict, meaning that order has been lost. Since that point, there is no way to recover the order.

More, you do not really use the dict, because you process everything sequentially, so you could just iterate:

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

(by Surachit SarkarCyrbiluser2357112Serge Ballesta)

참조 문서

  1. Can I convert a defaultdict or dict to an ordereddict in Python? (CC BY‑SA 2.5/3.0/4.0)

#defaultdict #fasta #Python #bioinformatics #biopython






관련 질문

많이 중첩 된 defaultdict에서 물건을 계산하는보다 Pythonic 방법 (More Pythonic way of counting things in a heavily nested defaultdict)

GAE ndb에서 산세척 (Pickling on GAE ndb)

파이썬을 사용하여 구분된 문자열 목록을 트리/중첩 사전으로 변환 (convert a list of delimited strings to a tree/nested dict, using python)

Python에서 defaultdict 또는 dict를 Ordereddict로 변환할 수 있습니까? (Can I convert a defaultdict or dict to an ordereddict in Python?)

기본 사전의 각 키를 고유한 CSV 파일에 쓰기 (Writing each key in a default dict to a unique csv file)

TypeError: 첫 번째 인수는 호출 가능해야 합니다. defaultdict (TypeError: first argument must be callable, defaultdict)

defaultdict(list)를 Pandas DataFrame으로 변환하는 방법 (How to convert a defaultdict(list) to Pandas DataFrame)

여러 매개변수가 있는 defaultdict (defaultdict with multiple parameters)

함께 사용되는 Defaultdict 및 람다 함수 (Defaultdict and lambda function used together)

클래스/유형을 포함하지 않고 중첩된 defaultdict를 인쇄하는 방법은 무엇입니까? (How to print a nested defaultdict without including the class/type?)

dict에서 빈 세트를 제거하는 간단한 방법 (Simple way to remove empty sets from dict)

특정 키를 포함하는 많은 defaultdicts의 값 가져오기 (Getting the values of many defaultdicts that contains a certain key)







코멘트