list of dictionaries

George Thomas george at cc.gatech.edu
Wed Jun 27 21:57:52 EDT 2001


Hi,

That makes sense. However, to make sure I understand completely, I'll
list the steps in question.
Given: A single dict object, call it dict (how original!)
1. Start with empty list
2. Update fields of dict
3. append dict to list.
4. Update fields of dict.
5. append dict to list.
The thing I can't understand is: even though dict reflects the change in
(4), the append() operation seems to ignore it completely, giving me a
copy of the previous contents. Why does this happen ?
Thanks for the insight on the alternative solution. I guess I'll rest
easy when the issue above has an explanation :)
 
Emile van Sebille wrote:
> 
> It is appended.  That's why you see two copies of the same dict in the list.
> To get different dicts in the list, you *must* create new dicts for each
> entry.  Otherwise, each entry simply points to the same dict.  You can use
> the {}.copy method for this data, but be forewarned that you need to be
> careful for nested data structures.
> 
> dict_entry['a'] = a2
> dict_entry['b'] = b2
> dict_entry['c'] = c2
> dict_entry['d'] = d2
> sample_list.append(dict_entry.copy())

------------------------------------------------------------
George Thomas
reduce (lambda c,d:chr(ord(d)-2)+c, 'ofcpqkekhhC"zwpkN"fgtgyqR/pqjv{R')
------------------------------------------------------------



More information about the Python-list mailing list