dictionaries/pointers
Erik Max Francis
max at alcyone.com
Fri Oct 7 17:26:57 EDT 2005
Rob Conner 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?
Objects of type int are immutable in Python, so you'll need a helper
class to do this. Try something like:
>>> class Container:
... def __init__(self, value=None): self.value = value
... def get(self): return self.value
... def set(self, value): self.value = value
...
>>> one = Container(1)
>>> myDictionary = {}
>>> myDictionary['a'] = one
>>> myDictionary['b'] = one
>>> myDictionary['b'].set(3)
>>> print myDictionary['a'].get()
3
--
Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
Never make a promise or plan / Take a little love where you can
-- Florence, _Chess_
More information about the Python-list
mailing list