[Zope] Python Q: dynamic dictionary of dictionaries..
Paul Winkler
slinkp23@yahoo.com
Mon, 5 Nov 2001 14:33:27 -0500
On Mon, Nov 05, 2001 at 02:21:14PM -0500, zope@virtosi.com wrote:
> >>>test = {'us_lead': 0,
> >>> 'foreign_lead': 0,
> >>> 'us_gov_lead': 0,
> >>> 'foreign_lead': 0,
> >>> 'us_other': 0,
> >>> 'foreign_other': 0 }
>
> >>>for i in my_list:
> >>> hash_one = {i: ""}
> >>> hash_one[i] = test
>
> this seems to "reset" the value of has_one with each iteration instead of
> updating it?? the key should be different, why is this??
The first line in your "for" loop creates a new hash_one and discards
whatever was in hash_one previously. At the end of the loop, hash_one
will only contain one key - the last one in the loop.
Try this:
hash_one={}
for i in my_list:
hash_one[i] = test
But I suspect that will just lead you to a new puzzle: you now have a
dictionary (hash_one) whose keys all point to the same dictionary
(test). The problem is that I suspect you'll want to modify them
independently. And the first time you try it, if you do
hash_one['K1']['us_lead'] = 99, guess what ...
hash_one['k2']['us_lead'] is now also 99. I suspect that's not what
you want. In python, if you assign the same object to several names
(or in this case to several values in a dict.), you don't get a new
copy for each assignment unless you explicitly ask for one.
You can get a copy of a list by slicing the whole thing
(e.g. my_list[:]), or a copy of a dictionary by using its copy method
(e.g. mydict.copy()), but I like to be consistent and use the copy
module from the standard library for everything. Like so:
import copy
hash_one={}
for i in my_list:
hash_one[i] = copy.copy(test)
--
paul winkler
home: http://www.slinkp.com
music: http://www.reacharms.com
calendars: http://www.calendargalaxy.com