sudoer
sudoer

Reputation: 155

Linked keys in dictionary

I am trying to make, say foo and bar reference to the same object. This is the expected output:

# note that variable d is a dictionary
# d["foo"] and d["bar"] are both have a value of "hello"
print(d["foo"])
print(d["bar"])
d["foo"] = "world"
print(d["foo"])
print(d["bar"])

However, this shows:

hello
hello
world
hello

which is excepted.

But I want the output to be:

hello
hello
world
world

(note the last line is world not hello)

Please help.

Upvotes: 1

Views: 138

Answers (1)

mozway
mozway

Reputation: 261900

What you want is not possible, you would need to use an object that it mutable (e.g. a list):

d = {}
d['foo'] = ['hello']
d['bar'] = d['foo']

print(d['bar'])

d['foo'][0] = 'world'
print(d['bar'])

output:

['hello']
['world']

Upvotes: 2

Related Questions