How to Manually Count Nucleotides Using a Dictionary in Python

In this method, we count each nucleotide by creating a dictionary and updating it while looping through the DNA sequence. This approach does not require any extra modules and helps you understand how counting works step by step.

Code
dna = “ATGCGCATG”

counts = {}

for base in dna:

    if base in counts:

        counts[base] += 1

    else:

        counts[base] = 1

print(counts)

 

Code (shorter version)
dna = “ATGCGCATG”

counts = {}

for base in dna:

counts[base] = counts[base] + 1 if base in counts else 1

print(counts)

 

Step-by-Step Explanation

  1. Store the DNA Sequence
dna = “ATGCGCATG”

We first store the DNA sequence in a variable called dna.

  1. Create an Empty Dictionary
counts = {}

An empty dictionary is created to store the count of each nucleotide.

  • Key → the nucleotide (A, T, G, or C)
  • Value → how many times it appears
  1. Loop Through Each Nucleotide
for base in dna:

The for loop goes through every character in the DNA string one by one.

 

In each iteration, the current character is stored in the variable base.

  1. Check and Update the Count
if base in counts:

    counts[base] += 1

else:

    counts[base] = 1

This is the core logic:

  • If the nucleotide already exists in the dictionary → increase its count by 1.
  • If the nucleotide does not exist yet → add it to the dictionary with a count of 1.
  1. Print the Final Result
print(counts)
Output:
{‘A’: 2, ‘T’: 2, ‘G’: 3, ‘C’: 2}

We have generated a dictionary named counts which has the value {‘A’: 2, ‘T’: 2, ‘G’: 3, ‘C’: 2}.

counts: {‘A’: 2, ‘T’: 2, ‘G’: 3, ‘C’: 2}

How the Dictionary Builds Up

StepCurrent BaseAction TakenDictionary State
1AAdd A with count 1{‘A’: 1}
2TAdd T with count 1{‘A’: 1, ‘T’: 1}
3GAdd G with count 1{‘A’: 1, ‘T’: 1, ‘G’: 1}
4CAdd C with count 1{‘A’: 1, ‘T’: 1, ‘G’: 1, ‘C’: 1}
5GIncrease G to 2{‘A’: 1, ‘T’: 1, ‘G’: 2, ‘C’: 1}
6CIncrease C to 2{‘A’: 1, ‘T’: 1, ‘G’: 2, ‘C’: 2}
7AIncrease A to 2{‘A’: 2, ‘T’: 1, ‘G’: 2, ‘C’: 2}
8TIncrease T to 2{‘A’: 2, ‘T’: 2, ‘G’: 2, ‘C’: 2}
9GIncrease G to 3{‘A’: 2, ‘T’: 2, ‘G’: 3, ‘C’: 2}

Summary

This method works by:

  1. Creating an empty dictionary.
  2. Checking each nucleotide one by one.
  3. Either adding a new nucleotide or increasing the count of an existing one.

It is a clear and fundamental way to count items in Python before using more advanced tools like collections.Counter.

Author:

Leave a Reply

Your email address will not be published. Required fields are marked *