How to Count Nucleotides Using dict.get() in Python

This is a shorter and cleaner way to count nucleotides using a dictionary. Instead of writing an if-else block, we use the .get() method.

 

Code
dna = “ATGCGCATG”

counts = {}

for base in dna:

    counts[base] = counts.get(base, 0) + 1

print(counts)

 

Output:

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

Step-by-Step Explanation

 

  1. Store the DNA Sequence

 

dna = “ATGCGCATG”

We store the DNA sequence in the variable dna.

 

  1. Create an Empty Dictionary

 

counts = {}

 

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

 

  1. Loop Through Each Nucleotide

 

for base in dna:

 

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

 

Each character is stored in the variable base.

One can also declare the empty variable before the far loop:  

base = “”

for base in dna:

    counts[base] = counts.get(base, 0) + 1

 

The line base = “” simply gives the variable an initial value.

As soon as the for loop starts, it overwrites base with the first character of dna, so the empty string is never used in the counting.

  1. Update the Count Using .get()

 

counts[base] = counts.get(base, 0) + 1

 

This is the key line. Let’s break it down:

  • counts.get(base, 0)
    → Looks for the current nucleotide in the dictionary.
    → If it exists, it returns its current count.
    → If it does not exist, it returns 0 (the default value).
  • Then we add 1 to that number.
  • Finally, we store the new count back into the dictionary.

So this single line replaces the entire if-else block.

 

  1. Print the Result

 

print(counts)

 

Output:

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

 

How the Dictionary Builds Up

StepCurrent Basecounts.get(base, 0)New CountDictionary After Update
1A01{‘A’: 1}
2T01{‘A’: 1, ‘T’: 1}
3G01{‘A’: 1, ‘T’: 1, ‘G’: 1}
4C01{‘A’: 1, ‘T’: 1, ‘G’: 1, ‘C’: 1}
5G12{‘A’: 1, ‘T’: 1, ‘G’: 2, ‘C’: 1}
6C12{‘A’: 1, ‘T’: 1, ‘G’: 2, ‘C’: 2}
7A12{‘A’: 2, ‘T’: 1, ‘G’: 2, ‘C’: 2}
8T12{‘A’: 2, ‘T’: 2, ‘G’: 2, ‘C’: 2}
9G23{‘A’: 2, ‘T’: 2, ‘G’: 3, ‘C’: 2}

 

Summary

  • .get(base, 0) safely gets the current count (or 0 if the key doesn’t exist).
  • We add 1 and store it back in the dictionary.
  • This method is shorter and more Pythonic than using if-else.

 

Author:

Leave a Reply

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