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
- Store the DNA Sequence
| dna = “ATGCGCATG” |
We store the DNA sequence in the variable dna.
- Create an Empty Dictionary
| counts = {} |
An empty dictionary is created to store the count of each nucleotide.
- 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.
- 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.
- Print the Result
| print(counts) |
Output:
| {‘A’: 2, ‘T’: 2, ‘G’: 3, ‘C’: 2} |
How the Dictionary Builds Up
| Step | Current Base | counts.get(base, 0) | New Count | Dictionary After Update |
| 1 | A | 0 | 1 | {‘A’: 1} |
| 2 | T | 0 | 1 | {‘A’: 1, ‘T’: 1} |
| 3 | G | 0 | 1 | {‘A’: 1, ‘T’: 1, ‘G’: 1} |
| 4 | C | 0 | 1 | {‘A’: 1, ‘T’: 1, ‘G’: 1, ‘C’: 1} |
| 5 | G | 1 | 2 | {‘A’: 1, ‘T’: 1, ‘G’: 2, ‘C’: 1} |
| 6 | C | 1 | 2 | {‘A’: 1, ‘T’: 1, ‘G’: 2, ‘C’: 2} |
| 7 | A | 1 | 2 | {‘A’: 2, ‘T’: 1, ‘G’: 2, ‘C’: 2} |
| 8 | T | 1 | 2 | {‘A’: 2, ‘T’: 2, ‘G’: 2, ‘C’: 2} |
| 9 | G | 2 | 3 | {‘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.