简体   繁体   中英

How to create a new dictionary from an old dictionary with the same keys but different values using a for loop

I'm trying to use a dictionary to calculate the molecular weight and molecular formula of a strand of DNA. I don't want to update the dictionary, I just want to deposit the values of the dictionary into a new dictionary based upon how many characters are in a string. Here is a sample piece of code that I tried.

deoxy_cytosine_dict ={"one letter code":"C" ,  "C":9 , "H":14 ,"N":3 , "O":8  ,"P":"P", "molecular weight":227 }




sequence ="CCGTCACCGGCCAACAGTGTGCAGATGGCGCCACGATGGGCAATACGAGCTCAAGCCAGTCT"
C_count = sequence.count("C")
tuple_pairs = []
new_dict = {}
for i in deoxy_cytosine_dict.values():
    values_for_new_dict = i * C_count
    tuple_pairs.append(values_for_new_dict)
    new_dict.update(tuple_pairs)

print(new_dict)

I would like the code to output the new_dict with updated values:

new_dict:{"one letter code":"C", "C":9*C_count, "H":14*C_count,"N":3*C_count, "O":8*C_count, "P":"P", "molecular weight":227*C_count }

This code doesn't work, but I would like it to still keep the format of a dictionary, but just output the new values with the old keys still in tact. I feel like there is a very easy way to do this, but I'm just missing it from my knowledge base. Also, I'm aware of biopython, but I'm just trying to give myself more pieces of code to use and understand and this is more of a learning experience for me.

The code below demonstrates how to create a new dictionary, with the same keys as an old dictionary, but different values:

d1 = {
    "apple":1,
    "banana":2,
    "kiwi":3
}
d2 = dict.fromkeys(d1)
for key in d1.keys():
    d2[key] = d1[key]*70 +45
print(d1)
print(d2)

The output is:

{'apple': 1, 'banana': 2, 'kiwi': 3}
{'apple': 115, 'banana': 185, 'kiwi': 255}

The code below shows how to compute the total molecular weight of a strand of dna given specific weights for each individual letter. Note that the numbers shown below are wrong, but you can change those:

strand = "CCGTCACCGGCCAACAGTGTGC"

weights = {
    "C":1,
    "G":2,
    "T":3,
    "A":4
}

lamb = lambda letter: weights[letter]
strand_total_weight = sum(map(lamb, strand))
print(strand_total_weight) # prints `46`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM