list of dictionaries

Emile van Sebille emile at fenx.com
Wed Jun 27 18:19:43 EDT 2001


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())

Note that even here, a new dict is created, as you can verify with

print type(sample_list[0]), id(sample_list[0])
print type(sample_list[1]),id(sample_list[1])

HTH,

--

Emile van Sebille
emile at fenx.com

---------
"George Thomas" <george at cc.gatech.edu> wrote in message
news:3B3A58A1.AE09529 at cc.gatech.edu...
> Hi,
> I wanted to avoid the creation of a new dict per entry. What I haven't
> been able to understand is why the "updated" dict is not appended.
>
> ------------- Emile van Sebille wrote:
> >
> > Note changes below
> >
> > --
> >
> > Emile van Sebille
> > emile at fenx.com
> >
> > #This creates a single dict that gets appended each time
> > #by creating a new dict for each entry as per below
> > #you don't really need this anymore.
> >
> regards
> ------------------------------------------------------------
> George Thomas
> ------------------------------------------------------------
> reduce (lambda c,d:chr(ord(d)-2)+c, 'ofcpqkekhhC"zwpkN"fgtgyqR/pqjv{R')
> ------------------------------------------------------------





More information about the Python-list mailing list