The error you're encountering (KeyError: 'c') is due to the reverse_complement function not handling lowercase nucleotides in the genome sequence. The dictionary only includes mappings for uppercase letters, but the FASTA file likely contains lowercase bases (e.g., 'c', 'a', etc.).
✅ Fix: Update the reverse_complement function
Modify the reverse_complement function to support both uppercase and lowercase nucleotides:
def reverse_complement(seq):
"""Generate the reverse complement of a DNA sequence (case-insensitive)"""
complement = {
'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C', 'N': 'N',
'a': 't', 't': 'a', 'c': 'g', 'g': 'c', 'n': 'n'
}
return ''.join([complement[base] for base in reversed(seq)])
🔍 Explanation of the Fix
- Problem: The original dictionary only had uppercase keys (
'A', 'T', etc.), but the genome sequence might contain lowercase letters ('a', 'c', etc.).
- Solution: Add lowercase keys (
'a', 'c', etc.) to the complement dictionary so that the function can handle mixed-case or fully lowercase sequences.
- This ensures that when the function encounters a
'c', it finds 'g' in the dictionary instead of throwing a KeyError.
🧪 Optional: Validate Input Sequence
To make the function even more robust, you can add a validation step to skip or warn about unknown characters:
def reverse_complement(seq):
"""Generate the reverse complement of a DNA sequence (case-insensitive)"""
complement = {
'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C', 'N': 'N',
'a': 't', 't': 'a', 'c': 'g', 'g': 'c', 'n': 'n'
}
try:
return ''.join([complement[base] for base in reversed(seq)])
except KeyError as e:
raise ValueError(f"Unknown nucleotide {e} in sequence. Only A, T, C, G, and N are supported.")
✅ Final Notes
- After applying the fix, re-run your script. It should now handle both uppercase and lowercase nucleotides correctly.
- If you're still seeing issues, double-check that the FASTA file doesn't contain unsupported characters like
'U' or 'X'.
Let me know if you'd like help validating the FASTA file or handling additional edge cases!