dictionaries/pointers

Dave Hansen iddw at hotmail.com
Fri Oct 7 17:35:41 EDT 2005


On 7 Oct 2005 14:23:49 -0700, "Rob Conner" <rtconner at gmail.com> wrote:

>I dont know how to do this and can't think of a simple way to.
>
>All I want is a dictionary where two keys point to the same object.
>(to steal the ascii art from
>http://starship.python.net/crew/mwh/hacks/objectthink.html)
>I want sometihng like this:
>
>,------.       +-------+
>| dict |------>|+-----+|     +---+
>`------'       || "a" |+---->| 1 |
>               |+-----+|     +---+
>               |       |       ^
>               |+-----+|       |
>               || "b" |+-------'
>               |+-----+|
>               +-------+
>               |       |
>               |+-----+|     +---+
>               || "c" |+---->| 2 |
>               |+-----+|     +---+
>               +-------+
>
>Where if I change "a" or "b" to 3 the other one will change?
>Is this even possible? How would I do it?

A simple, ugly answer: Use a mutable object rather than a plain
integer.  Example:

>>> elt = [1]
>>> dict = {"a":elt, "b":elt, "c":[2]}
>>> print dict
{'a': [1], 'c': [2], 'b': [1]}
>>> dict["a"][0] = 3
>>> print dict
{'a': [3], 'c': [2], 'b': [3]}
>>> 

Regards,

                               -=Dave
-- 
Change is inevitable, progress is not.



More information about the Python-list mailing list