nested dictionary assignment goes too far

Ben Cartwright bencvt at gmail.com
Tue Jun 27 02:49:14 CEST 2006


Jake Emerson wrote:
> 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

The way you're currently defining your dict:
  rain_raw_dict =
dict.fromkeys(distinctID,{'N':-6999,'char_freq':-6999,...})

Is shorthand for:
  tmp = {'N':-6999,'char_freq':-6999,...}
  rain_raw_dict = {}
  for key in distinctID:
      rain_raw_dict[key] = tmp

Note that tmp is a *reference*.  Python does not magically create
copies for you; you have to be explicit.  Unless you want a shared
value, dict.fromkeys should only be used with an immutable value (e.g.,
int or str).

What you'll need to do is either:
  tmp = {'N':-6999,'char_freq':-6999,...}
  rain_raw_dict = {}
  for key in distinctID:
      # explicitly make a (shallow) copy of tmp
      rain_raw_dict[key] = dict(tmp)

Or more simply:
  rain_raw_dict = {}
  for key in distinctID:
      rain_raw_dict[key] = {'N':-6999,'char_freq':-6999,...}

Or if you're a one-liner kinda guy,
  rain_raw_dict = dict((key, {'N':-6999,'char_freq':-6999,...})
                       for key in distinctID)

--Ben




More information about the Python-list mailing list