nested dictionary assignment goes too far

Serge Orlov serge.orlov at gmail.com
Mon Jun 26 20:33:53 EDT 2006


On 26 Jun 2006 16:56:22 -0700, Jake Emerson <jake.emerson at onerain.com> wrote:
> I'm attempting to build a process that helps me to evaluate the
> performance of weather stations. The script below operates on an MS
> Access database, brings back some data, and then loops through to pull
> out statistics. One such stat is the frequency of reports from the
> stations ('char_freq'). I have a collection of methods that operate on
> the data to return the 'char_freq' and this works great. However, when
> the process goes to insert the unique 'char_freq' into a nested
> dictionary the value gets put into ALL of the sub-keys for all of the
> weather stations.

It's a sure sign you're sharing an object. In python, unless
specifically written, an assignment-like method doesn't create copies:

>>> d = dict.fromkeys([1,2,3],[4,5,6])
>>> id(d[1]) == id(d[2])
True

Instead of

>    rain_raw_dict =
> dict.fromkeys(distinctID,{'N':-6999,'char_freq':-6999,'tip1':-6999,'tip2':-6999,'tip3':-6999,'tip4':-6999,'tip5':-6999,'tip6':-6999,'lost_rain':-6999})

you should do something like this:

defaults = {'N':-6999,'char_freq':-6999,'tip1':-6999,'tip2':-6999,'tip3':-6999,'tip4':-6999,'tip5':-6999,'tip6':-6999,'lost_rain':-6999}
rain_raw_dict = {}
for ID in [110,140,650,1440]:
    rain_raw_dict[ID] = defaults.copy()



More information about the Python-list mailing list