dinucleotide count and frequency
<p>Im trying to find the dinuc count and frequencies from a sequence in a text file, but my code is only outputting single nucleotide counts.</p>

<pre><code>e = "ecoli.txt"

ecnt = {}

with open(e) as seq:
    for line in seq:
        for word in line.split():
            for i in range(len(seqr)):
                dinuc = (seqr[i] + seqr[i:i+2])
                for dinuc in seqr:
                    if dinuc in ecnt:
                        ecnt[dinuc] += 1
                    else:
                        ecnt[dinuc] = 1  

for x,y in ecnt.items():
    print(x, y)
</code></pre>

<p>Sample input: "AAATTTCGTCGTTGCCC"</p>

<p>Sample output:
AA:2
TT:3
TC:2
CG:2
GT:2
GC:1
CC:2</p>

<p>Right now, Im only getting single nucleotides for my output:</p>

<p>C 83550600
A 60342100
T 88192300
G 92834000</p>

<p>For the nucleotides that repeat i.e. "AAA", the count has to return all possible combinations of consecutive 'AA', so the output should be 2 rather than 1. It doesnt matter what order the dinucleotides are listed, I just need all combinations, and for the code to return the correct count for the repeated nucleotides. I was asking my TA and she said that my only problem was getting my 'for' loop to add the dinucleotides to my dictionary, and I think my range may or may not be wrong. The file is a really big one, so the sequence is split up into lines.</p>

<p>Thank you so much in advance!!!</p>

<p>A perfect opportunity to use a <code>defaultdict</code>:</p>

<pre><code>from collections import defaultdict

file_name = "ecoli.txt"

dinucleotide_counts = defaultdict(int)

sequence = ""

with open(file_name) as file:
    for line in file:
        sequence += line.strip()

for i in range(len(sequence) - 1):
    dinucleotide_counts[sequence[i:i + 2]] += 1

for key, value in sorted(dinucleotide_counts.items()):
    print(key, value)
</code></pre>

python dictionary bioinformatics sequences