dictionaries/pointers

R

Rob Conner

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?
 
E

Erik Max Francis

Rob said:
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:
.... 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
 
D

Dave Hansen

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,264
Messages
2,571,326
Members
48,011
Latest member
BruceKersh

Latest Threads

Top