list of dictionaries

Emile van Sebille emile at fenx.com
Wed Jun 27 23:28:42 EDT 2001


You need to get a handle on mutable objects, labels, and references.

A dictionary is a mutable object.  When you append it to a list, you're
actually just putting a reference to the mutable object on the list, not the
object itself.  When the object changes, all references that point to the
object show the changes, as there is only one object.

>>> d = {1:1}
# create a dictionary object and keep a reference to it in d
>>> l = []
#create a list object
>>> l.append(d)
# put a reference to the dictionary object in the list
>>> l
[{1: 1}]
>>> d[1]=2
#change the dictioanry object
>>> l
[{1: 2}]
# the list reflects the change.
>>>

HTH,

--

Emile van Sebille
emile at fenx.com

---------
"George Thomas" <george at cc.gatech.edu> wrote in message
news:3B3A8F20.71F0DE04 at cc.gatech.edu...
> 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 ?

Double check your results here.  The list contains two references the the
single resulting dict.


> 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