Issue
I am playing with python just to learn. I have a dictionary
chrom_freq_0
{'A': 27.5,
'A+': 29.14,
'B': 30.87,
'C': 16.35,
'C+': 17.32,
'D': 18.35,
'D+': 19.45,
'E': 20.6,
'F': 21.83,
'F+': 23.12,
'G': 24.5,
'G+': 25.96}
that I want to contain in another dictionary as several modified versions of itself (as well as an original version of itself) but I can't figure out how to iterate properly. It is only including the last item in each version of the modified dictionary dictionary.
This is my code
Chrom_Freq = {0 : chrom_frq_0}
for i in range (1, 9):
for note, freq in chrom_freq_0.iteritems():
Chrom_Freq[i] = {note : freq*(2**i)}
I get this:
Chrom_Freq
--->
{0: {'A': 27.5,
'A+': 29.14,
'B': 30.87,
'C': 16.35,
'C+': 17.32,
'D': 18.35,
'D+': 19.45,
'E': 20.6,
'F': 21.83,
'F+': 23.12,
'G': 24.5,
'G+': 25.96},
1: {'G+': 51.92},
2: {'G+': 103.84},
3: {'G+': 207.68},
4: {'G+': 415.36},
5: {'G+': 830.72},
6: {'G+': 1661.44},
7: {'G+': 3322.88},
8: {'G+': 6645.76}}
Solution
Each assignment to Chrom_Freq[i]
replaces the value from the previous assignment.
In order to accumulate the contents you need to update the existing one if the key exists:
if i in Chrom_Freq:
Chrom_Freq[i].update({note : freq*(2**i)})
else:
Chrom_Freq[i] = {note : freq*(2**i)}
Answered By - Alain T.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.