jorgehumberto
jorgehumberto

Reputation: 1097

Summing values from Python Dictionary

I am using Python to sum random star spectra to increase their signal to noise ratio. One of the keywords of these spectra header contains the integration time for the spectrum. When I sum the spectra I want the keyword of the resulting spectrum to be updated with the sum of the integration times of each spectrum I used. For that, I use the following code:

for kk in range(0,NumberOfSpectra):             # main cycle
       TotalIntegrationTime = 0.0
       for item in RandomSpectraList:                       # secondary cycle
           SpectrumHeader = SpectraFullList[item]['head']         #1
           TotalIntegrationTime += SpectrumHeader['EXPTIME']

       SpectrumHeader['EXPTIME'] = TotalIntegrationTime               #2

    SaveHeaderFunction(SpectrumHeader, kk)

the problem I am having, is that when the main cycle loops, SpectrumHeader does not get reset when I re-assign it in #1 and shows the value it had in #2. Any ideas on why this happens and how to fix it?

NumberOfSpectra is provided by the user, RandomSpectraList is a list of random spectra by name. SpectraFullList contains the spectra and has keys 'head' and 'spec'.

Upvotes: 0

Views: 153

Answers (1)

Gijs van Oort
Gijs van Oort

Reputation: 152

Are you aware of the fact during line #2, SpectrumHeader still points to an element of SpectraFullList? They are the really the same object. So, when executing line #2 you are essentially modifying SpectraFullList. I guess that is not what you want and it may be the cause of your problem.

In order to solve it, insert the following line before #2:

SpectrumHeader = SpectraFullList[item]['head'].copy()

Upvotes: 1

Related Questions