Dictionaries as records

Thomas Jensen thomasNO at SPAM.obscure.dk
Wed Dec 19 10:58:12 EST 2001


"Bill Wilkinson" <bwilk_97 at yahoo.com> wrote in
news:F82U7.28866$t07.4111647 at twister.midsouth.rr.com: 

> "John Roth"
>> In this case, you have one copy of each of your input
>> strings, not 15000 copies! The memory usage should be pretty close
>> to pure dictionary overhead. 
> 
> I don't see how that can be. If they were all copies of the same
> reference, wouldn't a change in one record be reflected in all? 
> Below I make a change to one record and the others remain the same:

Strings are immutable - it is not possible to change a string.
Consider the following:

First create a list of 3 items. Actually the list contains 3 references 
to the same string object! (I'll be using a list instead of a dict, but 
there should be no difference).
   >>> list = ['abc'] * 3
Lets see the memory address of this string object.
   >>> [id(item) for item in list]
   [135450912, 135450912, 135450912]
The same as expected.

Now lets change the reference of the second item in list.  Note that we 
are not changing the string object with id 135450912 - we are changing 
a property of the list, i.e. the reference at position 1.
   >>> list[1] = 'def'

Let's see the addresses again:
   >>> [id(item) for item in list]
   [135450912, 135452512, 135450912]
Notice that the second element now refers to another memory address.

>>>>tbl[1]["g11"]  #original value 'ldjfljdfkjdf'
>>>> tbl[1]["g11"] = "f"  #change rec one to 'f'/ tbl[1]["g11"]   
>>>> #it's value is different now. 'f' tbl[2]["g11"]    #rec 2
>>>> remains the same. 
> 'ldjfljdfkjdf'
> 
> Now the question. Am I misunderstanding what is happening above?

I think you are mistaken changing a string with changing a reference in 
a list, dict, etc.

-- 
Thomas Jensen



More information about the Python-list mailing list