I was going through some basic gene encoding techniques and came across a problem:
My dictionary should look something like :
codon_dict= {
"A": {
"A": {
"A": 0.0,
"T": 0.0,
"G": 0.0,
"C": 0.0
},
"T": {
"A": 0.0,
"T": 0.0,
"G": 0.0,
"C": 0.0
},
"G": {
"A": 0.0,
"T": 0.0,
"G": 0.0,
"C": 0.0
},
"C": {
"A": 0.0,
"T": 0.0,
"G": 0.0,
"C": 0.0
}
},
"T": {
"A": {
"A": 0.0,
"T": 0.0,
"G": 0.0,
"C": 0.0
},
"T": {
"A": 0.0,
"T": 0.0,
"G": 0.0,
"C": 0.0
},
"G": {
"A": 0.0,
"T": 0.0,
"G": 0.0,
"C": 0.0
},
"C": {
"A": 0.0,
"T": 0.0,
"G": 0.0,
"C": 0.0
}
},
"G": {
"A": {
"A": 0.0,
"T": 0.0,
"G": 0.0,
"C": 0.0
},
"T": {
"A": 0.0,
"T": 0.0,
"G": 0.0,
"C": 0.0
},
"G": {
"A": 0.0,
"T": 0.0,
"G": 0.0,
"C": 0.0
},
"C": {
"A": 0.0,
"T": 0.0,
"G": 0.0,
"C": 0.0
}
},
"C": {
"A": {
"A": 0.0,
"T": 0.0,
"G": 0.0,
"C": 0.0
},
"T": {
"A": 0.0,
"T": 0.0,
"G": 0.0,
"C": 0.0
},
"G": {
"A": 0.0,
"T": 0.0,
"G": 0.0,
"C": 0.0
},
"C": {
"A": 0.0,
"T": 0.0,
"G": 0.0,
"C": 0.0
}
}
}
Instead of hard coding this, is there any way to construct it from lists? or iterate through a for loop and construct the same?
that is code_dict["A"]["A"]["A"] should return me 0.0
CodePudding user response:
Try itertools.product
:
from itertools import product
s = "ATGC"
out = {}
for x, y, z in product(s, repeat=3):
out.setdefault(x, {}).setdefault(y, {})[z] = 0.0
print(out)
Prints:
{
"A": {
"A": {"A": 0.0, "T": 0.0, "G": 0.0, "C": 0.0},
"T": {"A": 0.0, "T": 0.0, "G": 0.0, "C": 0.0},
"G": {"A": 0.0, "T": 0.0, "G": 0.0, "C": 0.0},
"C": {"A": 0.0, "T": 0.0, "G": 0.0, "C": 0.0},
},
"T": {
"A": {"A": 0.0, "T": 0.0, "G": 0.0, "C": 0.0},
"T": {"A": 0.0, "T": 0.0, "G": 0.0, "C": 0.0},
"G": {"A": 0.0, "T": 0.0, "G": 0.0, "C": 0.0},
"C": {"A": 0.0, "T": 0.0, "G": 0.0, "C": 0.0},
},
"G": {
"A": {"A": 0.0, "T": 0.0, "G": 0.0, "C": 0.0},
"T": {"A": 0.0, "T": 0.0, "G": 0.0, "C": 0.0},
"G": {"A": 0.0, "T": 0.0, "G": 0.0, "C": 0.0},
"C": {"A": 0.0, "T": 0.0, "G": 0.0, "C": 0.0},
},
"C": {
"A": {"A": 0.0, "T": 0.0, "G": 0.0, "C": 0.0},
"T": {"A": 0.0, "T": 0.0, "G": 0.0, "C": 0.0},
"G": {"A": 0.0, "T": 0.0, "G": 0.0, "C": 0.0},
"C": {"A": 0.0, "T": 0.0, "G": 0.0, "C": 0.0},
},
}