problem with dictionaries within lists

Grant Hallam gupsmail at ihatespam.shaw.ca
Wed Sep 25 10:30:50 EDT 2002


The problem with blanking out the dictionary with dict{} is that it wipes
the keys out.  As the loop goes through it assigns the matching second
half of the list to a matching key.  If you insert a print statement on
the dict you can see the values in the dict are changing.  Thus while it
is the same dict the key values within the dict are different.  Thats why
I'm somewhat confused as to why its the same dic value.  As for the tabs,
I'll have the editor replace them with 4 spaces.  Didn't notice the
problem in PAN :)

On Wed, 25 Sep 2002 02:11:14 -0700, Alex Martelli wrote:

> Grant Hallam wrote:
>         ...
>>  However, the list seems to get populated with the same dictionary
>         ...
>> webdatabaselist.append(dict)
> 
> Of course -- you ARE appending the same dict over ands over (AFAICT --
> you're probably using tabs for indentation, making your code hard to
> comprehend for those who read news with KDE's KNode [or MS's OE] as tabs
> don't show there... use spaces, NOT tabs...).
> 
> Anyway, you probably need something like:
> 
> webdatabaselist.append(dict.copy())
> dict = {}
> 
> either might suffice, but generally you'll need to copy the current dict
> AND make dict empty for the next leg of the loop, if I get the general
> drift.  If you do rebind name dict to {} for the next leg, then you
> don't need the call to the copy method.
> 
> 
> Alex



More information about the Python-list mailing list